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
F
be the active function object. - Assert:
F
has a[[Promise]]
internal slot whose value is an Object. - Let
promise
beF.[[Promise]]
. - Let
alreadyResolved
beF.[[AlreadyResolved]]
. - If
alreadyResolved.[[Value]]
istrue
, returnundefined
. - Set
alreadyResolved.[[Value]]
totrue
. - If
SameValue(resolution, promise)
istrue
, then- Let
selfResolutionError
be a newly createdTypeError
object. - Return
RejectPromise(promise, selfResolutionError)
.
- Let
- If
Type(resolution)
is not Object, then- Return
FulfillPromise(promise, resolution)
.
- Return
- Let
then
beGet(resolution, "then")
. - If
then
is an abrupt completion, then- Return
RejectPromise(promise, then.[[Value]])
.
- Return
- Let
thenAction
bethen.[[Value]]
. - If
IsCallable(thenAction)
isfalse
, then- Return
FulfillPromise(promise, resolution)
.
- Return
- Let
thenJobCallback
beHostMakeJobCallback(thenAction)
. - Let
job
beNewPromiseResolveThenableJob(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?"