简体   繁体   中英

When does an async task start in javascript?

Suppose a javascript task makes an async call. eg xhr.send(stuff)

  1. Does the (async) send begin in another thread immediately? or
  2. Does the send not begin until the current task is complete?

I am pretty sure it is (2) the latter but is this behavior covered by a spec or is it just the typical implementation. In a similar vein... Is the creation of a listener considered a synchronous call? Is there a specification covering this?

This question was mostly answered by @Alnitak, https://stackoverflow.com/a/17439761/345427 , https://youtu.be/8aGhZQkoFbQ and definitively by https://www.w3.org/TR/html51/webappapis.html#event-loops

The implementations can vary somewhat but the semantics seem to be as outlined in this summary.

  1. The async call (typically) causes execution to begin in a separate thread immediately. [eg xhr.send()]
  2. The event listener creation happens synchronously. [eg xhr.addEventListener()]
  3. When the async task completes a new task, representing the async result is added to the task-queue
  4. The event-loop reads the task-queue and evaluates the next task
  5. The async result has an associated callback which checks the listeners registered for the result.

Here is an example of how an async task works. https://chromium.googlesource.com/chromium/blink.git/+/99b8c9800ac123eddc3e199088d22569c5294b22/Source/core/xml/XMLHttpRequest.cpp

As you can see from the code there are several places where tasks are added to the task queue, dispatchEvent() gets called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM