async nodejs execution order

前端 未结 2 1900
慢半拍i
慢半拍i 2021-01-14 01:34

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 e

相关标签:
2条回答
  • 2021-01-14 02:01

    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.

    0 讨论(0)
  • 2021-01-14 02:19

    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

    0 讨论(0)
提交回复
热议问题