Skip to content

Instantly share code, notes, and snippets.

@adjavaherian
Created April 20, 2016 21:46
Show Gist options
  • Save adjavaherian/93a7824f34c74377a8882d56a6a3e58f to your computer and use it in GitHub Desktop.
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
// 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