Understanding the Execution Timing of Promise Constructor Callbacks
In JavaScript, when constructing a Promise using the new Promise syntax, the question arises as to when the body of the provided callback is executed. This question delves into the intricacies of Promise execution.
The body of the Promise constructor callback is executed synchronously, as per the ECMAScript specification. Immediately upon creation, the Promise invokes its executor function with the resolve and reject functions as arguments.
This synchronous execution implies that the code within the callback is run right away, even before the invocation of any asynchronous operations, such as the setTimeout used in your example. Therefore, doSomeWork() is called instantaneously after the Promise is constructed.
The asynchronous nature of setTimeout is independent of the Promise construction process. The callback provided to setTimeout will be scheduled to run after the specified delay, regardless of the Promise's timing.
The above is the detailed content of When Does a Promise Constructor\'s Callback Execute?. For more information, please follow other related articles on the PHP Chinese website!