Wednesday, June 5, 2024
106
rated 0 times [  109] [ 3]  / answers: 1 / hits: 33382  / 7 Years ago, wed, february 8, 2017, 12:00:00

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?


More From » ecmascript-6

 Answers
27

Immediately, yes, by specification.


From the MDN:



The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object)



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):




  1. 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.


[#59016] Tuesday, February 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrellhunterm

Total Points: 82
Total Questions: 109
Total Answers: 98

Location: Vietnam
Member since Sun, Oct 18, 2020
4 Years ago
;