Skip to content

Instantly share code, notes, and snippets.

@ljharb
Created December 29, 2013 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljharb/8174372 to your computer and use it in GitHub Desktop.
Save ljharb/8174372 to your computer and use it in GitHub Desktop.
Handling the results of multiple async ops with JS.
var promises = [
async1(),
async2(),
asyncN()
];
/* jQuery: warning, won't swallow exceptions */
var deferred = $.Deferred();
$.when.apply($, promises)
.done(function () { deferred.resolve(promises); })
.fail(function () { deferred.reject(promises); });
return deferred.promise();
/* Q: Promises/A+ compliant, plus more */
/* will resolve with an array of all values
or reject on first failure */
var all = Q.all(promises);
/* or, to wait for all to finish: */
var handleResults = function (results) {
results.forEach(function (result) {
if (result.state === "fulfilled") {
var value = result.value;
} else {
var reason = result.reason;
}
});
};
Q.allSettled(promises).then(handleResults);
/* Note that with solely a spec-compliant Promise, you'd have to write the code to aggregate with arrays yourself. Luckily, there's libraries to do that for you! */
@aredridel
Copy link

Yeah, maybe I'm weird, but I see about the same amount of complexity each way.

I'll keep thinking about it.

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