Created
January 12, 2021 15:15
-
-
Save pete-rai/fecc4de7ebe6c8c18418aef933e5a3bf to your computer and use it in GitHub Desktop.
An example of using Javascript Promises to ensure that a set of asyncronous steps are always performed in the specified order and strictly one after another.
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
/* | |
An example of using Javascript Promises to ensure that a set of asyncronous | |
steps are always performed in the specified order and strictly one after | |
another. | |
*/ | |
// --- some async function that takes some time to complete | |
function step(param) { // must return a promise | |
return new Promise((resolve) => { // using setTimeout here is just an example - your async function might be a web request or a database lookup | |
setTimeout(() => { | |
console.log(param); | |
resolve(); | |
}, Math.random() * 1000); | |
}); | |
} | |
// --- the main sequence pump - returns a promise for when all steps are completed | |
function sequence(func, steps) { | |
let step = Promise.resolve(); | |
for (let i = 0; i < steps.length; i++) { | |
step = step.then(() => { | |
return func(steps[i]); | |
}); | |
} | |
return step; | |
} | |
// --- the main entry point | |
let sequenced = true; // try setting this to true and then false to see the difference in results | |
let params = ['four', 'score', 'and', 'seven', 'years', 'ago']; | |
if (sequenced) { | |
console.log('-- started in sequenced mode --') | |
sequence(step, params).then(() => console.log('-- finished --')); // these steps will always be done in order | |
} else { | |
console.log('-- started in unsequenced mode --') | |
for (let i = 0; i < params.length; i++) { // these steps will happen in an undetermined order | |
step(params[i]); | |
} | |
console.log('-- finished --') | |
} |
If you want a full-blown solution to method chaining in the face of asynchronous functions - see my other gist https://gist.github.com/pete-rai/fb197af2b0ec7838216c6728c3ba2468
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the output with
sequenced
set toTRUE
-- started in sequenced mode -- four score and seven years ago -- finished --
Here is the output with
sequenced
set toFALSE
-- started in unsequenced mode -- -- finished -- seven score ago and four years