Last active
May 5, 2020 13:01
-
-
Save guillaumegarcia13/954ff9232d5fb9bdaaeae7762539668d to your computer and use it in GitHub Desktop.
Serialize promises
This file contains hidden or 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
// See: https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence/31070150#31070150 | |
// https://decembersoft.com/posts/promises-in-serial-with-array-reduce/ | |
/* | |
* Serialize promises (or rather tasks because once created, a Promise starts executing immedialtely | |
*/ | |
const promiseSerializer = (tasks: Array<()=>Promise<any>>) => { | |
return tasks.reduce((promiseChain: Promise<any>, currentTask: ()=>Promise<any>) => { | |
return promiseChain.then(chainResults => | |
currentTask().then(currentResult => | |
[...chainResults, currentResult] | |
) | |
); | |
}, Promise.resolve([])); | |
}; | |
// Demo | |
const promiseFactory = (code: number, delay: number = 2500) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log(new Date().toISOString(), code); | |
resolve(code); | |
}, delay); | |
}) | |
}; | |
promiseSerializer([ | |
() => promiseFactory(42), | |
() => promiseFactory(43), | |
() => promiseFactory(44), | |
() => promiseFactory(45) | |
]).then(values => { console.log(new Date().toISOString(), 'Results', values); }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment