Skip to content

Instantly share code, notes, and snippets.

@guillaumegarcia13
Last active May 5, 2020 13:01
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 guillaumegarcia13/954ff9232d5fb9bdaaeae7762539668d to your computer and use it in GitHub Desktop.
Save guillaumegarcia13/954ff9232d5fb9bdaaeae7762539668d to your computer and use it in GitHub Desktop.
Serialize promises
// 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