Skip to content

Instantly share code, notes, and snippets.

@anvk
Created May 26, 2016 19:24
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 anvk/174137474dc07da6e7c2e1b142b38513 to your computer and use it in GitHub Desktop.
Save anvk/174137474dc07da6e7c2e1b142b38513 to your computer and use it in GitHub Desktop.
Sequential execution of Promises using Recursion
function asyncFunc(e) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(e), e * 1000);
});
}
const arr = [1, 2, 3];
function workMyCollection(arr, results = []) {
return new Promise((resolve, reject) => {
if (!arr.length) {
return resolve(results);
}
const [element, ...rest] = arr;
console.log(`element is ${element}`);
asyncFunc(element)
.then((result) => {
results.push(result);
if (!rest.length) {
return resolve(results);
}
workMyCollection(rest, results)
.then(resolve)
.catch(console.error);
});
});
}
workMyCollection(arr, [])
.then(result => console.log(`FINAL RESULT is ${result}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment