p-queue icon indicating copy to clipboard operation
p-queue copied to clipboard

Helper method to emulate add(() => {})

Open snario opened this issue 6 years ago • 5 comments

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.

snario avatar Sep 11 '19 17:09 snario

Doesn't .onIdle do pretty much what you want?

kevva avatar Sep 30 '19 19:09 kevva

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).

snario avatar Oct 01 '19 03:10 snario

You should use await queue.onIdle() since it returns a promise. Same with queue.add() really.

kevva avatar Oct 01 '19 16:10 kevva

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.

snario avatar Oct 03 '19 06:10 snario

I have a separate hacky workaround by the way:

const d = new Deferred();
const p1 = queue.add(() => { d.resolve(); ... });
const waitPromise = d.promise;

snario avatar Oct 03 '19 06:10 snario