Skip to content

Instantly share code, notes, and snippets.

@mraxus
Created August 25, 2015 23:51
Show Gist options
  • Save mraxus/45046e30bb1be836dd0e to your computer and use it in GitHub Desktop.
Save mraxus/45046e30bb1be836dd0e to your computer and use it in GitHub Desktop.
Extend JQuery 1.x with whenAll that handles async call functions in objects or arrays. Returns a deferred that resolves in the same structure.
$.whenAll = function (deferreds) {
function isPromise(fn) {
return fn && typeof fn.then === 'function' &&
String($.Deferred().then) === String(fn.then);
}
var d = $.Deferred(),
keys = Object.keys(deferreds),
args = keys.map(function (k) {
return $.Deferred(function (d) {
var fn = deferreds[k];
(isPromise(fn) ? fn : $.Deferred(fn))
.done(d.resolve)
.fail(function (err) { d.reject(err, k); })
;
});
});
$.when.apply(this, args)
.done(function () {
var resObj = {},
resArgs = Array.prototype.slice.call(arguments);
resArgs.forEach(function (v, i) { resObj[keys[i]] = v; });
d.resolve(resObj);
})
.fail(d.reject);
return d;
};
function genStuff (id, prob) {
return function (d) {
setTimeout(function () {
if (Math.random() < (prob === undefined ? 0.5 : prop)) {
console.log('Stuff ' + id + ' is done!');
d.resolve(id);
} else {
console.log('Stuff ' + id + ' FAILED');
d.reject(new Error());
}
}, Math.random() * 2000);
};
}
var reqObj = {
x: genStuff('x'),
y: genStuff('y'),
z: genStuff('z')
};
var reqArr = [genStuff(0.1), genStuff(1), genStuff(2)];
$.whenAll(reqObj)
.done(function (res) {
console.log('Success');
console.log(res);
})
.fail(function (firstFail, name) {
console.log('Fail for: ' + name);
console.log(firstFail);
});
$.whenAll(reqArr)
.done(function (res) {
console.log('Success');
console.log(res);
})
.fail(function (firstFail, name) {
console.log('Fail for: ' + name);
console.log(firstFail);
});
@mraxus
Copy link
Author

mraxus commented Aug 26, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment