Skip to content

Instantly share code, notes, and snippets.

@fluency03
Forked from cpdean/map_reduce.js
Created March 20, 2017 22:10
Show Gist options
  • Select an option

  • Save fluency03/b6ba2557b2e7bc2feadbf86df003a8c3 to your computer and use it in GitHub Desktop.

Select an option

Save fluency03/b6ba2557b2e7bc2feadbf86df003a8c3 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);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment