Created
November 22, 2024 06:05
-
-
Save mnvr/16b8b9c4d663ab26876833598df003e7 to your computer and use it in GitHub Desktop.
A simple promise queue in JavaScript to serialize the execution of a bunch of 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
// A promise queue | |
const q = [] | |
const add = (task) => { | |
let handlers; | |
const p = new Promise((...args) => (handlers = args)); | |
q.push({task, handlers}); | |
if (q.length == 1) next(); | |
return p; | |
} | |
const next = () => { | |
const item = q[0]; | |
if (!item) return; | |
const {task, handlers} = item; | |
task().then(...handlers).finally(() => { | |
q.shift(); | |
next(); | |
}); | |
} | |
// Some code to test it. | |
const wait = () => new Promise((res) => setTimeout(res, Math.random() * 2000)); | |
makePromise = async (p) => { | |
console.log(p, "start"); | |
await wait(); | |
if (p % 2) throw new Error(`${p} rejecting`) | |
console.log(p, "end"); | |
return p ** 2; | |
} | |
const watch = (p, n) => { | |
p.then((z) => console.log(n, "fullfilled with", z), (e) => console.log(n, "rejected with", e.message)); | |
console.log(n, "add"); | |
} | |
main = async () => { | |
console.log("go", "a"); | |
for (let i = 0; i < 10; i++) { | |
watch(add(() => makePromise(i)), i); | |
await wait(); | |
} | |
console.log("go", "b"); | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment