Skip to content

Instantly share code, notes, and snippets.

@cpdean
Last active August 29, 2015 13:56
Show Gist options
  • Save cpdean/9095616 to your computer and use it in GitHub Desktop.
Save cpdean/9095616 to your computer and use it in GitHub Desktop.
q.js demo for having an arbitrary number of sub-promises generated from 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: 0}, {id: 3}]);
}, 1e3);
return deferred.promise;
}
// second query
function deferredPropertyLookup(x) {
var deferred = Q.defer();
setTimeout(function(){
console.log("second query starting " + x);
if(x != 0){
deferred.resolve(x);
}
else{
deferred.reject(new Error("such pains"));
}
}, 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
// todo: is it possible to salvage the sub promises that did manage
// to resolve?
console.log(a);
}, function(error){
console.log("Everything died!");
console.log(error.stack);
});
});
{
"name": "mapreduce-bug",
"version": "0.0.0",
"description": "",
"main": "map_reduce.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": " "
},
"author": "",
"license": "BSD",
"dependencies": {
"q": "1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment