Last active
August 29, 2015 13:56
-
-
Save alecperkins/8994490 to your computer and use it in GitHub Desktop.
Promise example with When.js (https://github.com/cujojs/when)
This file contains hidden or 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
// It's pretty straightforward to wrap callback-based functions in ones that | |
// use and return promises. | |
function readOne (url) { | |
var deferred = when.defer(); | |
httpRequest(url, function(response){ | |
deferred.resolve(response.length); | |
}); | |
// This promise represents the end result of the operation, and will | |
// be resolved when `httpRequest` calls `deferred.resolve` above. | |
// Once resolved, anything waiting for its result can continue. | |
return deferred.promise; | |
} | |
function sumAll (array) { | |
var sum = array.reduce(function(m,n) { return m + n }); | |
// Do something with `sum`. | |
} | |
var url_array = ["http://scripting.com", "http://google.com", "http://twitter.com"]; | |
// Call the request routine on each URL, collecting the promises into an | |
// `Array`. When all the promises are resolved, call `sumAll` with the results | |
// of each `readOne` call in an `Array`. (Note how the actual code is nearly | |
// the above comment, verbatim.) | |
var active_requests = url_array.map(readOne); | |
when.all(active_requests).then(sumAll); | |
// Code here will be called after the requests are initiated, but before | |
// `sumAll` is called. | |
// …or… | |
// Many promise libraries have utilities to consolidate those kinds of | |
// array operations. | |
when.map(url_array, readOne).then(sumAll); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment