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:
- Let
Fbe the active function object. - Assert:
Fhas a[[Promise]]internal slot whose value is an Object. - Let
promisebeF.[[Promise]]. - Let
alreadyResolvedbeF.[[AlreadyResolved]]. - If
alreadyResolved.[[Value]]istrue, returnundefined. - Set
alreadyResolved.[[Value]]totrue. - If
SameValue(resolution, promise)istrue, then- Let
selfResolutionErrorbe a newly createdTypeErrorobject. - Return
RejectPromise(promise, selfResolutionError).
- Let
- If
Type(resolution)is not Object, then- Return
FulfillPromise(promise, resolution).
- Return
- Let
thenbeGet(resolution, "then"). - If
thenis an abrupt completion, then- Return
RejectPromise(promise, then.[[Value]]).
- Return
- Let
thenActionbethen.[[Value]]. - If
IsCallable(thenAction)isfalse, then- Return
FulfillPromise(promise, resolution).
- Return
- Let
thenJobCallbackbeHostMakeJobCallback(thenAction). - Let
jobbeNewPromiseResolveThenableJob(promise, resolution, thenJobCallback). - Perform
HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]). - 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?"