Created
May 26, 2016 19:24
-
-
Save anvk/174137474dc07da6e7c2e1b142b38513 to your computer and use it in GitHub Desktop.
Sequential execution of Promises using Recursion
This file contains hidden or 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
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