Skip to content

Instantly share code, notes, and snippets.

@mLuby
Last active May 18, 2023 20:20
Show Gist options
  • Save mLuby/1a6b1d43c1b9f29ae146dce671486c62 to your computer and use it in GitHub Desktop.
Save mLuby/1a6b1d43c1b9f29ae146dce671486c62 to your computer and use it in GitHub Desktop.
Run Promisers (()=>Promise) in sequence rather than in parallel
type Promiser = () => Promise<any>;
function promisersSequenced([nextPromiser, ...otherPromisers]: Promiser[]) : Promise<any> {
return nextPromiser().then(() => otherPromisers.length && promisersSequenced(otherPromisers));
};
const responsePs: Promise<any>[] = [...new Array(3)].map((_, i) => new Promise(resolve => setTimeout(() => resolve(console.log("P idx:" + i)), 100 - i * 10)));
const responsePfs: Promiser[] = [...new Array(3)].map((_, i) => () => new Promise(resolve => setTimeout(() => resolve(console.log("Pf idx:" + i)), 100 - i * 10)));
(async function mainPs () {
console.log("Started");
await Promise.allSettled(responsePs).then(() => console.log("done Promise.allSettled"));
await promisersSequenced(responsePfs).then(() => console.log("done promisersSequenced"));
})();
@mLuby
Copy link
Author

mLuby commented May 18, 2023

To demo, click run at the TypeScript Playground: https://tinyurl.com/promisersSequenced.

[LOG]: "Started" 
[LOG]: "P  idx:2" 
[LOG]: "P  idx:1" 
[LOG]: "P  idx:0" 
[LOG]: "done Promise.allSettled" 
[LOG]: "Pf idx:0" 
[LOG]: "Pf idx:1" 
[LOG]: "Pf idx:2" 
[LOG]: "done promisersSequenced" 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment