Skip to content Skip to sidebar Skip to footer

Is Resolve Function Passed To Promise Executor Async?

I have the following code: function myPromiseFunc() { return new Promise((resolve) => { resolve(Promise.resolve(123)); }); } As we know Promise.resolve method resolves

Solution 1:

According to the specification of the resolve function passed to the executor in new Promise((resolve, reject) => ...):

When a promise resolve function is called with argument resolution, the following steps are taken:

  1. Let F be the active function object.
  2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  3. Let promise be F.[[Promise]].
  4. Let alreadyResolved be F.[[AlreadyResolved]].
  5. If alreadyResolved.[[Value]] is true, return undefined.
  6. Set alreadyResolved.[[Value]] to true.
  7. If SameValue(resolution, promise) is true, then
    1. Let selfResolutionError be a newly created TypeError object.
    2. Return RejectPromise(promise, selfResolutionError).
  8. If Type(resolution) is not Object, then
    1. Return FulfillPromise(promise, resolution).
  9. Let then be Get(resolution, "then").
  10. If then is an abrupt completion, then
    1. Return RejectPromise(promise, then.[[Value]]).
  11. Let thenAction be then.[[Value]].
  12. If IsCallable(thenAction) is false, then
    1. Return FulfillPromise(promise, resolution).
  13. Let thenJobCallback be HostMakeJobCallback(thenAction).
  14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback).
  15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  16. Return undefined.

Lots of technical jargon, but the most important bits for your question is that resolution is the value you passed to it. If it's (roughly) a non-Promise, you'll end up either in 8.1 (for non-objects) or 12.1 (for non-callable objects), which will all immediately fulfill the promise. If you passed a value with a then function (e.g. a Promise), it'll do all the steps starting from 13 where it basically queues up the .then and follows the whole "my fulfillment depends on another Promise's fulfillment".

Post a Comment for "Is Resolve Function Passed To Promise Executor Async?"