Created
September 26, 2019 20:36
-
-
Save stephen-james/456c2abbd98fa4da1377a9b14f143f1f to your computer and use it in GitHub Desktop.
Promise Pattern: Loop helper function to sequentially loop through an array of promises
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
console.clear(); | |
const loop = (arrayOfPromises, guard) => { | |
if (arrayOfPromises.length && (!guard || guard(arrayOfPromises[0]))) { | |
return arrayOfPromises.shift()().then(() => { | |
return loop(arrayOfPromises, guard); | |
}) | |
} | |
return Promise.resolve(); | |
} | |
const longOp = () => new Promise((resolve, reject) => { | |
console.log('longOp'); | |
setTimeout(resolve, 200); | |
}); | |
const ops = Array.from(Array(10)).map(() => longOp); | |
loop(ops) | |
.then(() => console.log('done')) | |
.catch(() => console.log('whooops')) | |
.finally(() => console.log('finally')) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment