Skip to content

Instantly share code, notes, and snippets.

@zaach
Last active December 20, 2015 17:19
Show Gist options
  • Save zaach/6168215 to your computer and use it in GitHub Desktop.
Save zaach/6168215 to your computer and use it in GitHub Desktop.
Map reduce with p-promises, based on https://gist.github.com/kriskowal/359801
// Map/Reduce with Promises
var p = require("p-promise");
// to simulate a long latency, promise-returning API
var delay = function (timeout) {
var deferred = p.defer();
setTimeout(function () {
deferred.resolve();
}, timeout);
return deferred.promise;
};
var sum = [0,1,2,3,4,5,6,7,8,9]
.map(function (n) {
return delay(1000).then(function () {
return n;
});
})
// at this point, we have an array of promises
// where each will eventually resolve to a number
// for the first iteration of reduce, sum will be the promise of
// the first number, i.e. 0
.reduce(function (sum, n) {
return n.then(function (n) {
return sum.then(function (sum) {
return sum + n;
});
});
});
sum.then(function (sum) {
console.log(sum);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment