Skip to content

Instantly share code, notes, and snippets.

@brandoncorbin
Last active November 8, 2019 16:47
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 brandoncorbin/05e5c22fde4c785fb57f90dd4f927a8b to your computer and use it in GitHub Desktop.
Save brandoncorbin/05e5c22fde4c785fb57f90dd4f927a8b to your computer and use it in GitHub Desktop.
Brandon Corbin's PromiseStep - a bunch of promises one at a time
/**
* 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