Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active March 3, 2017 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/9415f44b8e7ac733b87b883804db789f to your computer and use it in GitHub Desktop.
Save bradoyler/9415f44b8e7ac733b87b883804db789f to your computer and use it in GitHub Desktop.
Promise Collection Waterfall
const collection = [{id:'A'},{id:'B'},{id:'C'},{id:'D'}];
function doStuff(val) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(val);
}, 1000);
});
}
var promises = collection.reduce((acc, curr) => {
return acc.then((res) => {
return doStuff(curr).then(result => {
console.log('> id:'+ result.id + ' '+ new Date().getSeconds());
res.push(result);
return res;
});
});
}, Promise.resolve([]));
promises.then(console.log);
// Jsbin: https://jsbin.com/wifonol/3/edit?js,console
// Example OUTPUT:
// > id:A 46
// > id:B 47
// > id:C 48
// > id:D 49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment