Skip to content

Instantly share code, notes, and snippets.

@stevenocchipinti
Created October 13, 2023 03:54
Show Gist options
  • Save stevenocchipinti/29b1a7ee72a93e82b12c8658739e2990 to your computer and use it in GitHub Desktop.
Save stevenocchipinti/29b1a7ee72a93e82b12c8658739e2990 to your computer and use it in GitHub Desktop.
Sequential promises
// https://jrsinclair.com/articles/2019/how-to-run-async-js-in-parallel-or-sequential/
const job = (name, delay) =>
new Promise((res) => {
setTimeout(() => {
console.log(`Job(${name}) resolving after ${delay}`);
res();
}, delay);
});
// This does NOT work :(
["a", "b", "c"].forEach(async (i) => {
await job(i, 1000);
});
// This DOES work :)
for (const i of ["a", "b", "c"]) {
await job(i, 1000);
}
// These also work, but are ahrder to read imho
["a", "b", "c"].reduce(
(a, i) => a.then(() => job(i, 1000)),
Promise.resolve(null)
);
["a", "b", "c"].reduce(async (a, i) => {
await a;
return job(i, 1000);
}, Promise.resolve(null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment