Skip to content

Instantly share code, notes, and snippets.

@stephen-james
Created September 26, 2019 20:36
Show Gist options
  • Save stephen-james/456c2abbd98fa4da1377a9b14f143f1f to your computer and use it in GitHub Desktop.
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
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