Home > Web Front-end > JS Tutorial > Is the Promise Constructor Callback Executed Synchronously or Asynchronously?

Is the Promise Constructor Callback Executed Synchronously or Asynchronously?

Linda Hamilton
Release: 2024-10-30 17:26:26
Original
758 people have browsed it

Is the Promise Constructor Callback Executed Synchronously or Asynchronously?

Asynchronous Execution of Promise Constructor Callback

Question:

In the following code snippet:

<code class="python">function y(resolve, reject)
{
  console.log("Result");
  resolve();
}  

var promise = new Promise(y);</code>
Copy after login

Will the y function execute asynchronously or synchronously?

Answer:

The execution of the promise constructor callback depends on the specific implementation of the Promises/A specification.

The ES6 specification, in Section 25.4.3.1, states that:

"If executor does not throw an exception, the Promise object must be constructed in two steps:"

  1. The executor function must be called with three arguments:

    • resolve(): A function that the executor can call to fulfill the promise.
    • reject(): A function that the executor can call to reject the promise.
    • this: Reserved for future use.
  2. The executor function must return synchronously.

However, the subsequent execution of .then() calls on the promise is always asynchronous. This is evident in Section 25.4.5.3.1 of the ES6 specification, which describes the "PerformPromiseThen" algorithm:

"If the value of promise's [[PromiseState]] internal slot is "fulfilled", ..."
"...Perform EnqueueJob("PromiseJobs", PromiseReactionJob, «fulfillReaction, value»)."

Similarly, if the promise is rejected, the algorithm performs an asynchronous job enqueue.

Conclusion:

Therefore, the function passed to the promise constructor is executed synchronously, while subsequent .then() calls are always executed asynchronously according to the ES6 specification.

The above is the detailed content of Is the Promise Constructor Callback Executed Synchronously or Asynchronously?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template