Created
April 20, 2016 21:46
-
-
Save adjavaherian/93a7824f34c74377a8882d56a6a3e58f to your computer and use it in GitHub Desktop.
Example of using reduce with promises and closure to create async results in series
This file contains 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
// async_series.js | |
// example of using reduce with promises and closure to create async results in series | |
var q = require('Q'); | |
var results = [1, 2, 3, 4, 5]; | |
function workCollection(arr) { | |
return arr.reduce(function(promise, item, index) { | |
return promise.then(function(result) { | |
return (function(i, r, idx){ | |
setTimeout(function(){ | |
console.log('item', i, 'result', r, 'index', idx); | |
}, 1000 * idx); | |
return true | |
})(item, result, index); | |
}); | |
}, q().then(function(){return true})); | |
} | |
q() | |
.then(function(){ | |
//console.log('then one test'); | |
}) | |
.then(function(){ | |
//console.log('then 2 test'); | |
workCollection(results); | |
}) | |
.catch(function(err){ | |
console.log(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment