p-queue
p-queue copied to clipboard
Helper method to emulate add(() => {})
As far as I can tell, there is no way to get a promise that resolves for all items that are currently in the queue to finish (even if new ones are added later). A hacky workaround is const p = q.add(() => {}) which does get you this, but at the expense of adding an item to the queue.
Doesn't .onIdle do pretty much what you want?
When I was testing this I noticed that if I do something like this:
const queue = new Queue({ concurrency: 1 });
const p1 = queue.add(() => { ... });
const p2 = queue.add(() => { ... });
const waitPromise = queue.onIdle();
const p3 = queue.add(() => { ... });
If p2 has not yet begun executing when p3 is assigned, then waitPromise will only resolve after p3 begins executing. But what I need is for waitPromise to resolve when p2 begins executing (i.e., when the queue was idle at the point that onIdle was called).
You should use await queue.onIdle() since it returns a promise. Same with queue.add() really.
My use case requires me to add to many queues simultaneously, not that code snippet precisely. Specifically what I need is for a promise to be added to n queues at the same time, and wait for everything to be finished in every queue that it was added to before running that promise.
I have a separate hacky workaround by the way:
const d = new Deferred();
const p1 = queue.add(() => { d.resolve(); ... });
const waitPromise = d.promise;