Suppose I have the following code constructing a Promise
:
function doSomethingAsynchronous() {
return new Promise((resolve) => {
const result = doSomeWork();
setTimeout(() => {
resolve(result);
}), 100);
});
}
At which point in time is doSomeWork()
called? Is it immediately after or as the Promise
is constructed? If not, is there something additional I need to do explicitly to make sure the callback is run?
It is called synchronously, yes, by specification.
From the MDN:
The
executor
is called synchronously (as soon as thePromise
is constructed) with theresolveFunc
andrejectFunc
functions as arguments.
This is defined in the ECMAScript specification (of course, it's harder to read...) here (Step 9 as of this edit, showing that the executor is called synchronously):
- Let completion be Completion(Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »)).
(my emphasis)
This guarantee may be important, for example when you're preparing several promises you then pass to all
or race
, or when your executors have synchronous side effects.