Skip to content

Instantly share code, notes, and snippets.

@cpdean
Created January 27, 2014 23:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cpdean/8659630 to your computer and use it in GitHub Desktop.
Save cpdean/8659630 to your computer and use it in GitHub Desktop.
q.js demo for merging the results of an arbitrary number of promises generated by an initial promise.
// @cpdean
// demonstrates how to have one promise kick off
// an additional arbitrary number of promises, and
// then merge their results down again after
// all the promises are complete.
var Q = require('q'); // "q": "~1.0.0"
// initial query that generates seed data for more work to be done
function fakeQuery(){
var deferred = Q.defer();
setTimeout(function(){
console.log("first query complete");
deferred.resolve([{id: 1}, {id: 2}, {id: 3}]);
}, 1e3);
return deferred.promise;
}
// second query
function deferredPropertyLookup(x) {
var deferred = Q.defer();
setTimeout(function(){
console.log("next query complete on " + x);
deferred.resolve(x);
}, 1e3);
return deferred.promise;
}
fakeQuery().then(function(results){
// `results` could be an arbitrary number of things
// to do more work on
// then concurrently run the lookup function with its
// post processing step in then()
var with_properties = results.map(function(e){
return deferredPropertyLookup(e.id).then(function(found){
return {id: e.id, prop: found};
});
});
return Q.all(with_properties).done(function(a){
// print the results when the lookups and processing are done
console.log(a);
});
});
@neodon
Copy link

neodon commented Sep 4, 2015

Here is a snippet I use when I need to run an arbitrary number of promises one at a time sequentially. This is handy if you are making a lot of API calls and don't want to exceed rate or concurrent request limits.

function runPromiseSequence(items) {
  return items.map(function(item) {
    // Have to wrap this in a function to generate a promise for each item
    return function() {
      // return a value or promise
      return item.doSomethingAsync();
    };
  }).reduce(Q.when, Q());
}

The function will return a promise chain for each item in the array, like ...then(function(item[0] { ... }).then(function(item[1]) { ... }) etc and you can add to the end of the chain to do something after all the other promises are resolved sequentially.

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