Created
December 29, 2013 20:20
-
-
Save ljharb/8174372 to your computer and use it in GitHub Desktop.
Handling the results of multiple async ops with JS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! */ |
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
Yes,
Q.all
returns a promise, as doesQ.allSettled
and$.when
.Here's a pretty straightforward way to report all errors so you can roll back if necessary: (obviously it's N loops so you could do it more efficiently, but I'm always willing to sacrifice efficiency for readability)
As for "easier" versus "harder", it's that with callback soup (ps i highly recommend reading http://callbackhell.com) the cognitive load to understand what's happening throughout the program is much higher. With promises, even if it's the same amount of code, it's much simpler to look at a line and see "input leads to output" - which should be much simpler to understand.