Last active
November 8, 2019 16:47
-
-
Save brandoncorbin/05e5c22fde4c785fb57f90dd4f927a8b to your computer and use it in GitHub Desktop.
Brandon Corbin's PromiseStep - a bunch of promises one at a time
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
/** | |
* PromiseStep | |
* Like promise.all, but one at a time. | |
* | |
* - Basic | |
* | |
* PromiseStep([1,2,3], (row)=>{ | |
* return Promise.resolve(row) | |
* }.then((finished)=>{ | |
* console.log("All Done", finished); | |
* }) | |
* | |
* - With a Status Update | |
* | |
* PromiseStep([1,2,3], (row)=>{ | |
* return Promise.resolve(row) | |
* }, (status)=>{ | |
* console.log("Status", status) | |
* }).then((finished)=>{ | |
* console.log("All Done", finished); | |
* }) | |
* | |
*/ | |
let PromiseStep = (rows, promiseFunction, onChange) => { | |
onChange = onChange || function() {}; // a status callback | |
return new Promise((resolve, reject) => { | |
let finished = []; | |
// Create recurisve function to run | |
let run = () => { | |
// if finished is less than rows, we should run again. | |
if (finished.length < rows.length) { | |
// fire on change | |
onChange({ step: finished.length, total: rows.length, done: false }); | |
// Fire off promise function | |
promiseFunction(rows[finished.length]) | |
.then(res => { | |
// push results to finished | |
finished.push(res); | |
// run again | |
run(); | |
}) | |
.catch(e => { | |
// push error to finished - so we continue the flow | |
finished.push(e.message); | |
// run again | |
run(); | |
}); | |
} else { | |
// Finished running all steps | |
onChange({ step: finished.length, total: rows.length, done: true }); | |
// done | |
resolve(finished); | |
} | |
}; | |
// Kick off initial run | |
run(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment