Search code examples
javascriptecmascript-6promisees6-promise

When is the body of a Promise constructor callback executed?


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?


Solution

  • It is called synchronously, yes, by specification.

    From the MDN:

    The executor is called synchronously (as soon as the Promise is constructed) with the resolveFunc and rejectFunc 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):

    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.