4

When does processItem start executing. Does it start as soon as some items are pushed onto the queue? Or must the for loop finish before the first item on the queue starts executing?

var processItem = function (item, callback) {
    console.log(item)
    callback();
}


var myQueue = async.queue(processItem, 2)


for (index = 0; index < 1000; ++index) {
    myQueue.push(index)
}

2 Answers 2

4

The simple answer is that all of your tasks will be added to the queue, and then executed in a random (undefined) order.


background information, via https://github.com/caolan/async#queueworker-concurrency

queue(worker, concurrency)

Creates a queue object with the specified concurrency. Tasks added to the queue are processed in parallel (up to the concurrency limit). If all workers are in progress, the task is queued until one becomes available. Once a worker completes a task, that task's callback is called.


In other words, the order is undefined. If you require the tasks to be executed in a particular order, you should be using a different asynchronous primitive, such as series(tasks, [callback]) https://github.com/caolan/async#seriestasks-callback

Sign up to request clarification or add additional context in comments.

1 Comment

Clarified to relate to actual question
2

The current call stack must resolve before any asynchronous tasks will run. This means that the current function must run to completion (plus any functions that called that function, etc.) before any asynchronous operations will run. To answer your question directly: all items will be fully queued before the first one runs.

It might be helpful for you to read more about the JavaScript event loop: asynchronous jobs sit in the event queue, where they are handled one by one. Each job in the event queue causes the creation of the call stack (where each item in the stack is function call -- the first function is on the bottom, a function called within that first function is next-to-bottom, etc.). When the stack is fully cleared, the event loop processes the next event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.