Home >Web Front-end >JS Tutorial >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:"
The executor function must be called with three arguments:
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!