Home > Article > Web Front-end > Is the Promise Constructor’s Executor Function Synchronous or Asynchronous?
The Promise constructor accepts an executor function that defines the promise's fulfillment logic. One key question arises: is this executor function executed asynchronously or synchronously?
The behavior depends on the implementation of the Promise itself. However, the ES6 standard for Promises explicitly states that the fulfillment of a promise is always asynchronous.
Referring to the specification, we find that the executor function (in our case, the y function) is indeed executed synchronously (see step 10 of the specification). However, subsequent calls to .then() on the promise, such as promise.then(...), are always executed asynchronously (see step 8 of the "PerformPromiseThen" algorithm).
This asynchronous nature of .then() calls has several implications:
Consider the following code snippet:
<code class="javascript">function y(resolve, reject) { console.log("Result"); resolve(); } var promise = new Promise(y); promise.then(() => { console.log("Then handler executed after the synchronous execution of y"); });</code>
In this example, the y function is executed synchronously. However, the .then() handler is executed asynchronously once the event loop finishes. The output of this code will be:
Result Then handler executed after the synchronous execution of y
The above is the detailed content of Is the Promise Constructor’s Executor Function Synchronous or Asynchronous?. For more information, please follow other related articles on the PHP Chinese website!