Skip to content

Instantly share code, notes, and snippets.

@alecperkins
Last active August 29, 2015 13:56
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 alecperkins/8994490 to your computer and use it in GitHub Desktop.
Save alecperkins/8994490 to your computer and use it in GitHub Desktop.
Promise example with When.js (https://github.com/cujojs/when)
// 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