Skip to content
Advertisement

Javascript serial queue using async?

I have the following code:

JavaScript

When I run the code above I get this:

JavaScript

To do that I referenced this link:

https://caolan.github.io/async/v3/docs.html#queue

Could someone help me understand why the “serial” nature of the queue is not respected here? I set concurrency to 1 when I created serialQueue but, it looks like the queue isn’t really serializing the execution of the three functions passed in.

How can I get this queue to execute the three functions in order, so have 2 wait for 1 and 3 wait for 2…? Also, why is drained called before all functions are actually done executing?

Advertisement

Answer

There are a few things wrong here.

First: serialQueue.push(fx(...)) invokes fk immediately, does not wait for it to complete (you have no await) and places the return value (a promise) to your queue. You need to pass something that actually captures your intent so that it can be invoked later. There are lots of ways of doing this. You could pass arrays, in the form [func, arg1, arg2, ...], or you could pass functions in the form async () => { await func(arg1, arg2, ...) }, or you could use currying to produce a new function with predefined arguments, etc. Regardless…

Second: You don’t do anything with task in your queue’s handler. It’s your job to do something, the queue just passes in the items you’ve given it. If you want the items to be functions, you have to invoke something, and await the promise it returns, if that’s what you want the queue to do for you. Right now, you’re ignoring task entirely.

Something like this:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement