Embrace the asynchronous nature of JavaScript!
All of the following will return immediately, but have a single place for putting code you want to run after something has happened.
The methods I've outlined here are all for different use cases and are roughly ordered in terms of their complexity.
The different things are as follows:
- Waiting for some condition to become true
- Waiting for a set of methods to finish (in any order) before calling a single callback
- Running a series of asynchronous methods with shared state in a particular order before calling a callback
Wait
Waiting to see if some condition is true is useful where there isn't any accessible callback to tell you when something has finished executing.
This is a pretty basic implementation that assumes that the condition will become true at some point. With a few tweaks it could be expanded to be even more useful (for example, by setting a call limit). (I only wrote this one yesterday!)
function waitFor(predicate, successCallback) {
setTimeout(function () {
var result = predicate();
if (result !== undefined)
successCallback(result);
else
waitFor(predicate, successCallback);
}, 100);
}
Calling code:
beforeEach(function (done) {
selectListField('A field');
waitFor(function () {
var availableOptions = stores.scrapeStore(optionStore);
if (availableOptions.length !== 0)
return availableOptions;
}, done);
});
Here I'm calling something which loads an Ext JS 'store' and waiting till the store contains something before continuing (the beforeEach is a Jasmine test framework thing).
Wait for several things to complete
I also needed to run a single callback after a load of different methods finished. You can do that like this:
createWaitRunner = function (completionCallback) {
var callback = completionCallback;
var completionRecord = [];
var elements = 0;
function maybeFinish() {
var done = completionRecord.every(function (element) {
return element === true
});
if (done)
callback();
}
return {
getNotifier: function (func) {
func = func || function (){};
var index = elements++;
completionRecord[index] = false;
return function () {
func.applyTo(arguments);
completionRecord[index] = true;
maybeFinish();
}
}
}
};
Calling code:
var waiter = createWaitRunner(done);
filterList.bindStore = waiter.getNotifier();
includeGrid.reconfigure = waiter.getNotifier(function (store) {
includeStore = store;
});
excludeGrid.reconfigure = waiter.getNotifier(function (store) {
excludeStore = store;
});
You either just wait for the notifications or can also wrap other functions which use the values passed to the function. When all the methods are called then done
will be run.
Running asynchronous methods in order
I've used a different approach when I had a series of asynchronous methods to call in a row (again in tests). This is somewhat similar to something you can get in the Async library - series does about the same thing and I had a little read of that library first to see if it did what I wanted. I think mine has a nicer API for working with tests though (and it was fun to implement!).
// Provides a context for running asynchronous methods synchronously
// The context just provides a way of sharing bits of state
// Use 'run' to execute the methods. These should be methods that take a callback and optionally the context as arguments
// Note the callback is provided first, so you have the option of just partially applying your function to the arguments you want
// instead of having to wrap even simple functions in another function
// When adding steps you can supply either just a function or a variable name and a function
// If you supply a variable name then the output of the function (which should be passed into the callback) will be written to the context
createSynchronisedRunner = function (doneFunction) {
var context = {};
var currentPosition = 0;
var steps = [];
// This is the loop. It is triggered again when each method finishes
var runNext = function () {
var step = steps[currentPosition];
step.func.call(null,
function (output) {
step.outputHandler(output);
currentPosition++;
if (currentPosition === steps.length)
return;
runNext();
}, context);
};
var api = {};
api.addStep = function (firstArg, secondArg) {
var assignOutput;
var func;
// Overloads
if (secondArg === undefined) {
assignOutput = function () {
};
func = firstArg;
}
else {
var propertyName = firstArg;
assignOutput = function (output) {
context[propertyName] = output;
};
func = secondArg;
}
steps.push({
func: func,
outputHandler: assignOutput
});
};
api.run = function (completedAllCallback) {
completedAllCallback = completedAllCallback || function(){};
var lastStep = steps[steps.length - 1];
var currentHandler = lastStep.outputHandler;
lastStep.outputHandler = function (output) {
currentHandler(output);
completedAllCallback(context);
doneFunction();
};
runNext();
};
// This is to support more flexible use where you use a done function in a different scope to initialisation
// For example, the done of a test but create in a beforeEach
api.setDoneCallback = function (done) {
doneFunction = done;
};
return api;
};
Calling code:
beforeAll(function (done) {
var runner = createSynchronisedRunner(done);
runner.addStep('attachmentInformation', testEventService.getAttachmentCalled.partiallyApplyTo('cat eating lots of memory.jpg'));
runner.addStep('attachment', getAttachment.partiallyApplyTo("cat eating lots of memory.jpg"));
runner.addStep('noAttachment', getAttachment.partiallyApplyTo("somethingElse.jpg"));
runner.run(function (context) {
attachment = context.attachment;
noAttachment = context.noAttachment;
});
});
PartiallyApplyTo here is basically a renamed version of Douglas Crockford's implementation of Curry. A lot of the stuff I'm working with takes a callback as the final argument so simple calls can be done like this rather than having to wrap everything with an extra function.