Home >Web Front-end >JS Tutorial >When is the Promise Constructor\'s Callback Executed?
Synchronicity of Promise Constructor Callback
In the context of Promise construction, you may wonder about the execution timing of the callback provided to the Promise constructor. Let's explore this question in detail.
Consider the following snippet:
function doSomethingAsynchronous() { return new Promise((resolve) => { const result = doSomeWork(); setTimeout(() => { resolve(result); }, 100); }); }
When constructing this Promise, at what point is doSomeWork() invoked?
As per the ECMAScript specification, the executor function (the callback provided to the constructor) is invoked synchronously upon Promise construction. This means that doSomeWork() will be executed immediately when the Promise is created, before the callback continues execution. This is what the MDN states:
The executor is called synchronously (as soon as the Promise is constructed) with the resolveFunc and rejectFunc functions as arguments.
The synchronous nature of the executor invocation is guaranteed by the specification. For instance, this guarantee is relevant when composing multiple promises using all or race, as well as when the executor has synchronous side effects.
The above is the detailed content of When is the Promise Constructor\'s Callback Executed?. For more information, please follow other related articles on the PHP Chinese website!