Created
October 13, 2023 03:54
-
-
Save stevenocchipinti/29b1a7ee72a93e82b12c8658739e2990 to your computer and use it in GitHub Desktop.
Sequential promises
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
// 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