Last active
December 20, 2015 17:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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