I'm starting to reuse this pattern, and was wondering if there was a more succinct/clear way to write it.
Given a function foo
taking a callback argument:
function foo(..., cb) { ... }
And function bar
which calls foo
with several different arguments taking a callback function of its own to be called when all the 'dependent' callbacks have been called, I write:
function bar(data, cb) {
var promises = [];
function createPromise() {
var p = $.Deferred();
promises.push(p);
return function() { p.resolve(); };
};
for (var i = 0; i < data.length; i++) {
foo(data[i], createPromise());
}
$.when.apply($, promises).then(cb);
}
I'm quite happy with the pattern, but the apply
and closure-returning-a-function make me suspect that there might be a simpler way of doing the same... Ideas?