Last active
September 12, 2023 19:30
-
-
Save dansalias/90d95944e5c33d9e18974d1901d203c4 to your computer and use it in GitHub Desktop.
Waiting for an empty queue
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
const queue: Set<Promise<unknown>> = new Set() | |
const queueEmpty = async (): Promise<void> => { | |
await Promise.all(queue) | |
if (queue.size) { | |
await queueEmpty() | |
} | |
} | |
const addPromiseToQueue = async (promise: Promise<unknown>): Promise<void> => { | |
queue.add(promise) | |
await promise | |
queue.delete(promise) | |
} | |
const test = async () => { | |
const asyncTask = (delay: number, duration: number): Promise<void> => | |
new Promise((resolve) => | |
setTimeout(() => { | |
console.log(`${delay}+${duration}ms task complete`) | |
resolve() | |
}, duration), | |
) | |
const addTaskToQueue = (delay: number, duration: number): void => { | |
if (delay) { | |
setTimeout(() => addPromiseToQueue(asyncTask(delay, duration)), delay) | |
} else { | |
addPromiseToQueue(asyncTask(0, duration)) | |
} | |
} | |
addTaskToQueue(0, 400) | |
addTaskToQueue(200, 400) | |
addTaskToQueue(0, 800) | |
addTaskToQueue(600, 2000) | |
await queueEmpty() | |
console.log('all tasks complete') | |
} | |
test() | |
// output: | |
// 0+400ms task complete | |
// 200+400ms task complete | |
// 0+800ms task complete | |
// 600+2000ms task complete | |
// all tasks complete |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment