Skip to content

Instantly share code, notes, and snippets.

@fodra
Forked from anvk/promises_reduce.js
Created June 12, 2018 07:02
Show Gist options
  • Save fodra/096e467abd55e3b4c2c3d1bcc5cd0976 to your computer and use it in GitHub Desktop.
Save fodra/096e467abd55e3b4c2c3d1bcc5cd0976 to your computer and use it in GitHub Desktop.
Sequential execution of Promises using reduce()
function asyncFunc(e) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(e), e * 1000);
});
}
const arr = [1, 2, 3];
let final = [];
function workMyCollection(arr) {
return arr.reduce((promise, item) => {
return promise
.then((result) => {
console.log(`item ${item}`);
return asyncFunc(item).then(result => final.push(result));
})
.catch(console.error);
}, Promise.resolve());
}
workMyCollection(arr)
.then(() => console.log(`FINAL RESULT is ${final}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment