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

Is the Promise Constructor Callback Executed Synchronously or Asynchronously?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 17:26:26696browse

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>

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!

Statement:
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