Last active
March 3, 2017 14:42
-
-
Save bradoyler/9415f44b8e7ac733b87b883804db789f to your computer and use it in GitHub Desktop.
Promise Collection Waterfall
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
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