27 Control Abstraction Objects
27.1 Iteration
27.1.1 Common Iteration Interfaces
An interface is a set of property keys whose associated values match a specific specification. Any object that provides all the properties as described by an interface's specification conforms to that interface. An interface is not represented by a distinct object. There may be many separately implemented objects that conform to any interface. An individual object may conform to multiple interfaces.
27.1.1.1 The Iterable Interface
The Iterable interface includes the property described in
| Property | Value | Requirements |
|---|---|---|
@@iterator
|
A function that returns an Iterator object. | The returned object must conform to the Iterator interface. |
27.1.1.2 The Iterator Interface
An object that implements the Iterator interface must include the property in
| Property | Value | Requirements |
|---|---|---|
|
|
A function that returns an IteratorResult object. |
The returned object must conform to the IteratorResult interface. If a previous call to the next method of an Iterator has returned an IteratorResult object whose next method of that object should also return an IteratorResult object whose |
Arguments may be passed to the next function but their interpretation and validity is dependent upon the target Iterator. The for-of statement and other common users of Iterators do not pass any arguments, so Iterator objects that expect to be used in such a manner must be prepared to deal with being called with no arguments.
| Property | Value | Requirements |
|---|---|---|
|
|
A function that returns an IteratorResult object. |
The returned object must conform to the IteratorResult interface. Invoking this method notifies the Iterator object that the caller does not intend to make any more next method calls to the Iterator. The returned IteratorResult object will typically have a return method. However, this requirement is not enforced.
|
|
|
A function that returns an IteratorResult object. |
The returned object must conform to the IteratorResult interface. Invoking this method notifies the Iterator object that the caller has detected an error condition. The argument may be used to identify the error condition and typically will be an exception object. A typical response is to throw the value passed as the argument. If the method does not throw, the returned IteratorResult object will typically have a |
Typically callers of these methods should check for their existence before invoking them. Certain ECMAScript language features including for-of, yield*, and array destructuring call these methods after performing an existence check. Most ECMAScript library functions that accept Iterable objects as arguments also conditionally call them.
27.1.1.3 The AsyncIterable Interface
The AsyncIterable interface includes the properties described in
| Property | Value | Requirements |
|---|---|---|
@@asyncIterator |
A function that returns an AsyncIterator object. | The returned object must conform to the AsyncIterator interface. |
27.1.1.4 The AsyncIterator Interface
An object that implements the AsyncIterator interface must include the properties in
| Property | Value | Requirements |
|---|---|---|
| A function that returns a promise for an IteratorResult object. |
The returned promise, when fulfilled, must fulfill with an object which conforms to the IteratorResult interface. If a previous call to the Additionally, the IteratorResult object that serves as a fulfillment value should have a |
Arguments may be passed to the next function but their interpretation and validity is dependent upon the target AsyncIterator. The for-await-of statement and other common users of AsyncIterators do not pass any arguments, so AsyncIterator objects that expect to be used in such a manner must be prepared to deal with being called with no arguments.
| Property | Value | Requirements |
|---|---|---|
| A function that returns a promise for an IteratorResult object. |
The returned promise, when fulfilled, must fulfill with an object which conforms to the IteratorResult interface. Invoking this method notifies the AsyncIterator object that the caller does not intend to make any more Additionally, the IteratorResult object that serves as a fulfillment value should have a |
|
| A function that returns a promise for an IteratorResult object. |
The returned promise, when fulfilled, must fulfill with an object which conforms to the IteratorResult interface. Invoking this method notifies the AsyncIterator object that the caller has detected an error condition. The argument may be used to identify the error condition and typically will be an exception object. A typical response is to return a rejected promise which rejects with the value passed as the argument. If the returned promise is fulfilled, the IteratorResult fulfillment value will typically have a |
Typically callers of these methods should check for their existence before invoking them. Certain ECMAScript language features including for-await-of and yield* call these methods after performing an existence check.
27.1.1.5 The IteratorResult Interface
The IteratorResult interface includes the properties listed in
| Property | Value | Requirements |
|---|---|---|
|
|
Either |
This is the result status of an iterator next method call. If the end of the iterator was reached |
|
|
Any |
If done is |
27.1.2 The %IteratorPrototype% Object
The
- has a [[Prototype]] internal slot whose value is
%Object.prototype% . - is an
ordinary object .
All objects defined in this specification that implement the Iterator interface also inherit from
The following expression is one way that ECMAScript code can access the
Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
27.1.2.1 %IteratorPrototype% [ @@iterator ] ( )
The following steps are taken:
- Return the
this value.
The value of the
27.1.3 The %AsyncIteratorPrototype% Object
The
- has a [[Prototype]] internal slot whose value is
%Object.prototype% . - is an
ordinary object .
All objects defined in this specification that implement the AsyncIterator interface also inherit from
27.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
The following steps are taken:
- Return the
this value.
The value of the
27.1.4 Async-from-Sync Iterator Objects
An Async-from-Sync Iterator object is an async iterator that adapts a specific synchronous iterator. There is not a named
27.1.4.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )
The abstract operation CreateAsyncFromSyncIterator takes argument syncIteratorRecord. It is used to create an async iterator
- Let asyncIterator be !
OrdinaryObjectCreate (%AsyncFromSyncIteratorPrototype% , « [[SyncIteratorRecord]] »). Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord.- Let nextMethod be !
Get (asyncIterator,"next" ). - Let iteratorRecord be the
Record { [[Iterator]]: asyncIterator, [[NextMethod]]: nextMethod, [[Done]]:false }. - Return iteratorRecord.
27.1.4.2 The %AsyncFromSyncIteratorPrototype% Object
The
- has properties that are inherited by all Async-from-Sync Iterator Objects.
- is an
ordinary object . - has a [[Prototype]] internal slot whose value is
%AsyncIteratorPrototype% . - has the following properties:
27.1.4.2.1 %AsyncFromSyncIteratorPrototype% .next ( [ value ] )
- Let O be the
this value. Assert :Type (O) is Object and O has a [[SyncIteratorRecord]] internal slot.- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let syncIteratorRecord be O.[[SyncIteratorRecord]].
- If value is present, then
- Let result be
IteratorNext (syncIteratorRecord, value).
- Let result be
- Else,
- Let result be
IteratorNext (syncIteratorRecord).
- Let result be
IfAbruptRejectPromise (result, promiseCapability).- Return !
AsyncFromSyncIteratorContinuation (result, promiseCapability).
27.1.4.2.2 %AsyncFromSyncIteratorPrototype% .return ( [ value ] )
- Let O be the
this value. Assert :Type (O) is Object and O has a [[SyncIteratorRecord]] internal slot.- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
- Let return be
GetMethod (syncIterator,"return" ). IfAbruptRejectPromise (return, promiseCapability).- If return is
undefined , then- Let iterResult be !
CreateIterResultObject (value,true ). - Perform !
Call (promiseCapability.[[Resolve]],undefined , « iterResult »). - Return promiseCapability.[[Promise]].
- Let iterResult be !
- If value is present, then
- Let result be
Call (return, syncIterator, « value »).
- Let result be
- Else,
- Let result be
Call (return, syncIterator).
- Let result be
IfAbruptRejectPromise (result, promiseCapability).- If
Type (result) is not Object, then- Perform !
Call (promiseCapability.[[Reject]],undefined , « a newly createdTypeError object »). - Return promiseCapability.[[Promise]].
- Perform !
- Return !
AsyncFromSyncIteratorContinuation (result, promiseCapability).
27.1.4.2.3 %AsyncFromSyncIteratorPrototype% .throw ( [ value ] )
- Let O be the
this value. Assert :Type (O) is Object and O has a [[SyncIteratorRecord]] internal slot.- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
- Let throw be
GetMethod (syncIterator,"throw" ). IfAbruptRejectPromise (throw, promiseCapability).- If throw is
undefined , then- Perform !
Call (promiseCapability.[[Reject]],undefined , « value »). - Return promiseCapability.[[Promise]].
- Perform !
- If value is present, then
- Let result be
Call (throw, syncIterator, « value »).
- Let result be
- Else,
- Let result be
Call (throw, syncIterator).
- Let result be
IfAbruptRejectPromise (result, promiseCapability).- If
Type (result) is not Object, then- Perform !
Call (promiseCapability.[[Reject]],undefined , « a newly createdTypeError object »). - Return promiseCapability.[[Promise]].
- Perform !
- Return !
AsyncFromSyncIteratorContinuation (result, promiseCapability).
27.1.4.2.4 Async-from-Sync Iterator Value Unwrap Functions
An async-from-sync iterator value unwrap function is an anonymous built-in function that is used by
When an async-from-sync iterator value unwrap function is called with argument value, the following steps are taken:
- Let F be the
active function object . - Return !
CreateIterResultObject (value, F.[[Done]]).
27.1.4.3 Properties of Async-from-Sync Iterator Instances
Async-from-Sync Iterator instances are ordinary objects that inherit properties from the
| Internal Slot | Description |
|---|---|
| [[SyncIteratorRecord]] |
A |
27.1.4.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability )
The abstract operation AsyncFromSyncIteratorContinuation takes arguments result and promiseCapability (a
- Let done be
IteratorComplete (result). IfAbruptRejectPromise (done, promiseCapability).- Let value be
IteratorValue (result). IfAbruptRejectPromise (value, promiseCapability).- Let valueWrapper be
PromiseResolve (%Promise% , value). IfAbruptRejectPromise (valueWrapper, promiseCapability).- Let steps be the algorithm steps defined in
Async-from-Sync Iterator Value Unwrap Functions . - Let length be the number of non-optional parameters of the function definition in
Async-from-Sync Iterator Value Unwrap Functions . - Let onFulfilled be !
CreateBuiltinFunction (steps, length,"" , « [[Done]] »). Set onFulfilled.[[Done]] to done.- Perform !
PerformPromiseThen (valueWrapper, onFulfilled,undefined , promiseCapability). - Return promiseCapability.[[Promise]].
27.2 Promise Objects
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
Any Promise object is in one of three mutually exclusive states: fulfilled, rejected, and pending:
-
A promise
pis fulfilled ifp.then(f, r)will immediately enqueue aJob to call the functionf. -
A promise
pis rejected ifp.then(f, r)will immediately enqueue aJob to call the functionr. - A promise is pending if it is neither fulfilled nor rejected.
A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected.
A promise is resolved if it is settled or if it has been “locked in” to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is unresolved if it is not resolved. An unresolved promise is always in the pending state. A resolved promise may be pending, fulfilled or rejected.
27.2.1 Promise Abstract Operations
27.2.1.1 PromiseCapability Records
A PromiseCapability Record is a
PromiseCapability Records have the fields listed in
| Field Name | Value | Meaning |
|---|---|---|
| [[Promise]] | An object | An object that is usable as a promise. |
| [[Resolve]] |
A |
The function that is used to resolve the given promise object. |
| [[Reject]] |
A |
The function that is used to reject the given promise object. |
27.2.1.1.1 IfAbruptRejectPromise ( value, capability )
IfAbruptRejectPromise is a shorthand for a sequence of algorithm steps that use a
- IfAbruptRejectPromise(value, capability).
means the same thing as:
- If value is an
abrupt completion , then- Perform ?
Call (capability.[[Reject]],undefined , « value.[[Value]] »). - Return capability.[[Promise]].
- Perform ?
- Else if value is a
Completion Record , set value to value.[[Value]].
27.2.1.2 PromiseReaction Records
The PromiseReaction is a
PromiseReaction records have the fields listed in
| Field Name | Value | Meaning |
|---|---|---|
| [[Capability]] |
A |
The capabilities of the promise for which this record provides a reaction handler. |
| [[Type]] |
|
The [[Type]] is used when [[Handler]] is |
| [[Handler]] |
A |
The function that should be applied to the incoming value, and whose return value will govern what happens to the derived promise. If [[Handler]] is |
27.2.1.3 CreateResolvingFunctions ( promise )
The abstract operation CreateResolvingFunctions takes argument promise. It performs the following steps when called:
- Let alreadyResolved be the
Record { [[Value]]:false }. - Let stepsResolve be the algorithm steps defined in
Promise Resolve Functions . - Let lengthResolve be the number of non-optional parameters of the function definition in
Promise Resolve Functions . - Let resolve be !
CreateBuiltinFunction (stepsResolve, lengthResolve,"" , « [[Promise]], [[AlreadyResolved]] »). Set resolve.[[Promise]] to promise.Set resolve.[[AlreadyResolved]] to alreadyResolved.- Let stepsReject be the algorithm steps defined in
Promise Reject Functions . - Let lengthReject be the number of non-optional parameters of the function definition in
Promise Reject Functions . - Let reject be !
CreateBuiltinFunction (stepsReject, lengthReject,"" , « [[Promise]], [[AlreadyResolved]] »). Set reject.[[Promise]] to promise.Set reject.[[AlreadyResolved]] to alreadyResolved.- Return the
Record { [[Resolve]]: resolve, [[Reject]]: reject }.
27.2.1.3.1 Promise Reject Functions
A promise reject function is an anonymous built-in function that has [[Promise]] and [[AlreadyResolved]] internal slots.
When a promise reject function is called with argument reason, 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 be F.[[Promise]].
- Let alreadyResolved be F.[[AlreadyResolved]].
- If alreadyResolved.[[Value]] is
true , returnundefined . Set alreadyResolved.[[Value]] totrue .- Return
RejectPromise (promise, reason).
The
27.2.1.3.2 Promise Resolve Functions
A promise resolve function is an anonymous built-in function that has [[Promise]] and [[AlreadyResolved]] internal slots.
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 be F.[[Promise]].
- Let alreadyResolved be F.[[AlreadyResolved]].
- If alreadyResolved.[[Value]] is
true , returnundefined . Set alreadyResolved.[[Value]] totrue .- If
SameValue (resolution, promise) istrue , then- Let selfResolutionError be a newly created
TypeError object. - Return
RejectPromise (promise, selfResolutionError).
- Let selfResolutionError be a newly created
- If
Type (resolution) is not Object, then- Return
FulfillPromise (promise, resolution).
- Return
- Let then be
Get (resolution,"then" ). - If then is an
abrupt completion , then- Return
RejectPromise (promise, then.[[Value]]).
- Return
- Let thenAction be then.[[Value]].
- If
IsCallable (thenAction) isfalse , then- Return
FulfillPromise (promise, resolution).
- Return
- Let thenJobCallback be
HostMakeJobCallback (thenAction). - Let job be
NewPromiseResolveThenableJob (promise, resolution, thenJobCallback). - Perform
HostEnqueuePromiseJob (job.[[Job]], job.[[Realm]]). - Return
undefined .
The
27.2.1.4 FulfillPromise ( promise, value )
The abstract operation FulfillPromise takes arguments promise and value. It performs the following steps when called:
Assert : The value of promise.[[PromiseState]] ispending .- Let reactions be promise.[[PromiseFulfillReactions]].
Set promise.[[PromiseResult]] to value.Set promise.[[PromiseFulfillReactions]] toundefined .Set promise.[[PromiseRejectReactions]] toundefined .Set promise.[[PromiseState]] tofulfilled .- Return
TriggerPromiseReactions (reactions, value).
27.2.1.5 NewPromiseCapability ( C )
The abstract operation NewPromiseCapability takes argument C. It attempts to use C as a resolve and reject functions. The Promise object plus the resolve and reject functions are used to initialize a new
- If
IsConstructor (C) isfalse , throw aTypeError exception. - NOTE: C is assumed to be a
constructor function that supports the parameter conventions of the Promiseconstructor (see27.2.3.1 ). - Let promiseCapability be the
PromiseCapability Record { [[Promise]]:undefined , [[Resolve]]:undefined , [[Reject]]:undefined }. - Let steps be the algorithm steps defined in
GetCapabilitiesExecutor Functions . - Let length be the number of non-optional parameters of the function definition in
GetCapabilitiesExecutor Functions . - Let executor be !
CreateBuiltinFunction (steps, length,"" , « [[Capability]] »). Set executor.[[Capability]] to promiseCapability.- Let promise be ?
Construct (C, « executor »). - If
IsCallable (promiseCapability.[[Resolve]]) isfalse , throw aTypeError exception. - If
IsCallable (promiseCapability.[[Reject]]) isfalse , throw aTypeError exception. Set promiseCapability.[[Promise]] to promise.- Return promiseCapability.
This abstract operation supports Promise subclassing, as it is generic on any
27.2.1.5.1 GetCapabilitiesExecutor Functions
A GetCapabilitiesExecutor function is an anonymous built-in function that has a [[Capability]] internal slot.
When a GetCapabilitiesExecutor function is called with arguments resolve and reject, the following steps are taken:
- Let F be the
active function object . Assert : F has a [[Capability]] internal slot whose value is aPromiseCapability Record .- Let promiseCapability be F.[[Capability]].
- If promiseCapability.[[Resolve]] is not
undefined , throw aTypeError exception. - If promiseCapability.[[Reject]] is not
undefined , throw aTypeError exception. Set promiseCapability.[[Resolve]] to resolve.Set promiseCapability.[[Reject]] to reject.- Return
undefined .
The
27.2.1.6 IsPromise ( x )
The abstract operation IsPromise takes argument x. It checks for the promise brand on an object. It performs the following steps when called:
- If
Type (x) is not Object, returnfalse . - If x does not have a [[PromiseState]] internal slot, return
false . - Return
true .
27.2.1.7 RejectPromise ( promise, reason )
The abstract operation RejectPromise takes arguments promise and reason. It performs the following steps when called:
Assert : The value of promise.[[PromiseState]] ispending .- Let reactions be promise.[[PromiseRejectReactions]].
Set promise.[[PromiseResult]] to reason.Set promise.[[PromiseFulfillReactions]] toundefined .Set promise.[[PromiseRejectReactions]] toundefined .Set promise.[[PromiseState]] torejected .- If promise.[[PromiseIsHandled]] is
false , performHostPromiseRejectionTracker (promise,"reject" ). - Return
TriggerPromiseReactions (reactions, reason).
27.2.1.8 TriggerPromiseReactions ( reactions, argument )
The abstract operation TriggerPromiseReactions takes arguments reactions (a
- For each element reaction of reactions, do
- Let job be
NewPromiseReactionJob (reaction, argument). - Perform
HostEnqueuePromiseJob (job.[[Job]], job.[[Realm]]).
- Let job be
- Return
undefined .
27.2.1.9 HostPromiseRejectionTracker ( promise, operation )
The
An implementation of HostPromiseRejectionTracker must complete normally in all cases. The default implementation of HostPromiseRejectionTracker is to unconditionally return an empty normal completion.
HostPromiseRejectionTracker is called in two scenarios:
- When a promise is rejected without any handlers, it is called with its operation argument set to
"reject" . - When a handler is added to a rejected promise for the first time, it is called with its operation argument set to
"handle" .
A typical implementation of HostPromiseRejectionTracker might try to notify developers of unhandled rejections, while also being careful to notify them if such previous notifications are later invalidated by new handlers being attached.
If operation is
27.2.2 Promise Jobs
27.2.2.1 NewPromiseReactionJob ( reaction, argument )
The abstract operation NewPromiseReactionJob takes arguments reaction and argument. It returns a new
- Let job be a new
Job Abstract Closure with no parameters that captures reaction and argument and performs the following steps when called:Assert : reaction is a PromiseReactionRecord .- Let promiseCapability be reaction.[[Capability]].
- Let type be reaction.[[Type]].
- Let handler be reaction.[[Handler]].
- If handler is
empty , then- If type is
Fulfill , let handlerResult beNormalCompletion (argument). - Else,
Assert : type isReject .- Let handlerResult be
ThrowCompletion (argument).
- If type is
- Else, let handlerResult be
HostCallJobCallback (handler,undefined , « argument »). - If promiseCapability is
undefined , thenAssert : handlerResult is not anabrupt completion .- Return
NormalCompletion (empty ).
Assert : promiseCapability is aPromiseCapability Record .- If handlerResult is an
abrupt completion , then- Let status be
Call (promiseCapability.[[Reject]],undefined , « handlerResult.[[Value]] »).
- Let status be
- Else,
- Let status be
Call (promiseCapability.[[Resolve]],undefined , « handlerResult.[[Value]] »).
- Let status be
- Return
Completion (status).
- Let handlerRealm be
null . - If reaction.[[Handler]] is not
empty , then- Let getHandlerRealmResult be
GetFunctionRealm (reaction.[[Handler]].[[Callback]]). - If getHandlerRealmResult is a normal completion, set handlerRealm to getHandlerRealmResult.[[Value]].
- Else, set handlerRealm to
the current Realm Record . - NOTE: handlerRealm is never
null unless the handler isundefined . When the handler is a revoked Proxy and no ECMAScript code runs, handlerRealm is used to create error objects.
- Let getHandlerRealmResult be
- Return the
Record { [[Job]]: job, [[Realm]]: handlerRealm }.
27.2.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )
The abstract operation NewPromiseResolveThenableJob takes arguments promiseToResolve, thenable, and then. It performs the following steps when called:
- Let job be a new
Job Abstract Closure with no parameters that captures promiseToResolve, thenable, and then and performs the following steps when called:- Let resolvingFunctions be
CreateResolvingFunctions (promiseToResolve). - Let thenCallResult be
HostCallJobCallback (then, thenable, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »). - If thenCallResult is an
abrupt completion , then- Let status be
Call (resolvingFunctions.[[Reject]],undefined , « thenCallResult.[[Value]] »). - Return
Completion (status).
- Let status be
- Return
Completion (thenCallResult).
- Let resolvingFunctions be
- Let getThenRealmResult be
GetFunctionRealm (then.[[Callback]]). - If getThenRealmResult is a normal completion, let thenRealm be getThenRealmResult.[[Value]].
- Else, let thenRealm be
the current Realm Record . - NOTE: thenRealm is never
null . When then.[[Callback]] is a revoked Proxy and no code runs, thenRealm is used to create error objects. - Return the
Record { [[Job]]: job, [[Realm]]: thenRealm }.
27.2.3 The Promise Constructor
The Promise
- is
%Promise% . - is the initial value of the
"Promise" property of theglobal object . - creates and initializes a new Promise object when called as a
constructor . - is not intended to be called as a function and will throw an exception when called in that manner.
- is designed to be subclassable. It may be used as the value in an
extendsclause of a class definition. Subclass constructors that intend to inherit the specified Promise behaviour must include asupercall to the Promiseconstructor to create and initialize the subclass instance with the internal state necessary to support thePromiseandPromise.prototypebuilt-in methods.
27.2.3.1 Promise ( executor )
When the Promise function is called with argument executor, the following steps are taken:
- If NewTarget is
undefined , throw aTypeError exception. - If
IsCallable (executor) isfalse , throw aTypeError exception. - Let promise be ?
OrdinaryCreateFromConstructor (NewTarget," , « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »).%Promise.prototype% " Set promise.[[PromiseState]] topending .Set promise.[[PromiseFulfillReactions]] to a new emptyList .Set promise.[[PromiseRejectReactions]] to a new emptyList .Set promise.[[PromiseIsHandled]] tofalse .- Let resolvingFunctions be
CreateResolvingFunctions (promise). - Let completion be
Call (executor,undefined , « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »). - If completion is an
abrupt completion , then- Perform ?
Call (resolvingFunctions.[[Reject]],undefined , « completion.[[Value]] »).
- Perform ?
- Return promise.
The executor argument must be a
The resolve function that is passed to an executor function accepts a single argument. The executor code may eventually call the resolve function to indicate that it wishes to resolve the associated Promise object. The argument passed to the resolve function represents the eventual value of the deferred action and can be either the actual fulfillment value or another Promise object which will provide the value if it is fulfilled.
The reject function that is passed to an executor function accepts a single argument. The executor code may eventually call the reject function to indicate that the associated Promise is rejected and will never be fulfilled. The argument passed to the reject function is used as the rejection value of the promise. Typically it will be an Error object.
The resolve and reject functions passed to an executor function by the Promise
27.2.4 Properties of the Promise Constructor
The Promise
- has a [[Prototype]] internal slot whose value is
%Function.prototype% . - has the following properties:
27.2.4.1 Promise.all ( iterable )
The all function returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejects with the reason of the first passed promise that rejects. It resolves all elements of the passed iterable to promises as it runs this algorithm.
- Let C be the
this value. - Let promiseCapability be ?
NewPromiseCapability (C). - Let promiseResolve be
GetPromiseResolve (C). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
GetIterator (iterable). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
PerformPromiseAll (iteratorRecord, C, promiseCapability, promiseResolve). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toIteratorClose (iteratorRecord, result). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return
Completion (result).
The all function requires its
27.2.4.1.1 GetPromiseResolve ( promiseConstructor )
The abstract operation GetPromiseResolve takes argument promiseConstructor. It performs the following steps when called:
Assert :IsConstructor (promiseConstructor) istrue .- Let promiseResolve be ?
Get (promiseConstructor,"resolve" ). - If
IsCallable (promiseResolve) isfalse , throw aTypeError exception. - Return promiseResolve.
27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseAll takes arguments iteratorRecord, constructor, resultCapability (a
Assert :IsConstructor (constructor) istrue .Assert :IsCallable (promiseResolve) istrue .- Let values be a new empty
List . - Let remainingElementsCount be the
Record { [[Value]]: 1 }. - Let index be 0.
- Repeat,
- Let next be
IteratorStep (iteratorRecord). - If next is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (next).- If next is
false , thenSet iteratorRecord.[[Done]] totrue .Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let valuesArray be !
CreateArrayFromList (values). - Perform ?
Call (resultCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be !
- Return resultCapability.[[Promise]].
- Let nextValue be
IteratorValue (next). - If nextValue is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (nextValue).- Append
undefined to values. - Let nextPromise be ?
Call (promiseResolve, constructor, « nextValue »). - Let steps be the algorithm steps defined in
.Promise.allResolve Element Functions - Let length be the number of non-optional parameters of the function definition in
.Promise.allResolve Element Functions - Let onFulfilled be !
CreateBuiltinFunction (steps, length,"" , « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »). Set onFulfilled.[[AlreadyCalled]] tofalse .Set onFulfilled.[[Index]] to index.Set onFulfilled.[[Values]] to values.Set onFulfilled.[[Capability]] to resultCapability.Set onFulfilled.[[RemainingElements]] to remainingElementsCount.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.- Perform ?
Invoke (nextPromise,"then" , « onFulfilled, resultCapability.[[Reject]] »). Set index to index + 1.
- Let next be
27.2.4.1.3 Promise.all Resolve Element Functions
A Promise.all resolve element function is an anonymous built-in function that is used to resolve a specific Promise.all element. Each Promise.all resolve element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.
When a Promise.all resolve element function is called with argument x, the following steps are taken:
- Let F be the
active function object . - If F.[[AlreadyCalled]] is
true , returnundefined . Set F.[[AlreadyCalled]] totrue .- Let index be F.[[Index]].
- Let values be F.[[Values]].
- Let promiseCapability be F.[[Capability]].
- Let remainingElementsCount be F.[[RemainingElements]].
Set values[index] to x.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let valuesArray be !
CreateArrayFromList (values). - Return ?
Call (promiseCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be !
- Return
undefined .
The Promise.all resolve element function is
27.2.4.2 Promise.allSettled ( iterable )
The allSettled function returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
- Let C be the
this value. - Let promiseCapability be ?
NewPromiseCapability (C). - Let promiseResolve be
GetPromiseResolve (C). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
GetIterator (iterable). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
PerformPromiseAllSettled (iteratorRecord, C, promiseCapability, promiseResolve). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toIteratorClose (iteratorRecord, result). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return
Completion (result).
The allSettled function requires its
27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord, constructor, resultCapability (a
Assert : !IsConstructor (constructor) istrue .Assert :IsCallable (promiseResolve) istrue .- Let values be a new empty
List . - Let remainingElementsCount be the
Record { [[Value]]: 1 }. - Let index be 0.
- Repeat,
- Let next be
IteratorStep (iteratorRecord). - If next is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (next).- If next is
false , thenSet iteratorRecord.[[Done]] totrue .Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let valuesArray be !
CreateArrayFromList (values). - Perform ?
Call (resultCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be !
- Return resultCapability.[[Promise]].
- Let nextValue be
IteratorValue (next). - If nextValue is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (nextValue).- Append
undefined to values. - Let nextPromise be ?
Call (promiseResolve, constructor, « nextValue »). - Let stepsFulfilled be the algorithm steps defined in
.Promise.allSettledResolve Element Functions - Let lengthFulfilled be the number of non-optional parameters of the function definition in
.Promise.allSettledResolve Element Functions - Let onFulfilled be !
CreateBuiltinFunction (stepsFulfilled, lengthFulfilled,"" , « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »). - Let alreadyCalled be the
Record { [[Value]]:false }. Set onFulfilled.[[AlreadyCalled]] to alreadyCalled.Set onFulfilled.[[Index]] to index.Set onFulfilled.[[Values]] to values.Set onFulfilled.[[Capability]] to resultCapability.Set onFulfilled.[[RemainingElements]] to remainingElementsCount.- Let stepsRejected be the algorithm steps defined in
.Promise.allSettledReject Element Functions - Let lengthRejected be the number of non-optional parameters of the function definition in
.Promise.allSettledReject Element Functions - Let onRejected be !
CreateBuiltinFunction (stepsRejected, lengthRejected,"" , « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »). Set onRejected.[[AlreadyCalled]] to alreadyCalled.Set onRejected.[[Index]] to index.Set onRejected.[[Values]] to values.Set onRejected.[[Capability]] to resultCapability.Set onRejected.[[RemainingElements]] to remainingElementsCount.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.- Perform ?
Invoke (nextPromise,"then" , « onFulfilled, onRejected »). Set index to index + 1.
- Let next be
27.2.4.2.2 Promise.allSettled Resolve Element Functions
A Promise.allSettled resolve element function is an anonymous built-in function that is used to resolve a specific Promise.allSettled element. Each Promise.allSettled resolve element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.
When a Promise.allSettled resolve element function is called with argument x, the following steps are taken:
- Let F be the
active function object . - Let alreadyCalled be F.[[AlreadyCalled]].
- If alreadyCalled.[[Value]] is
true , returnundefined . Set alreadyCalled.[[Value]] totrue .- Let index be F.[[Index]].
- Let values be F.[[Values]].
- Let promiseCapability be F.[[Capability]].
- Let remainingElementsCount be F.[[RemainingElements]].
- Let obj be !
OrdinaryObjectCreate (%Object.prototype% ). - Perform !
CreateDataPropertyOrThrow (obj,"status" ,"fulfilled" ). - Perform !
CreateDataPropertyOrThrow (obj,"value" , x). Set values[index] to obj.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let valuesArray be !
CreateArrayFromList (values). - Return ?
Call (promiseCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be !
- Return
undefined .
The Promise.allSettled resolve element function is
27.2.4.2.3 Promise.allSettled Reject Element Functions
A Promise.allSettled reject element function is an anonymous built-in function that is used to reject a specific Promise.allSettled element. Each Promise.allSettled reject element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.
When a Promise.allSettled reject element function is called with argument x, the following steps are taken:
- Let F be the
active function object . - Let alreadyCalled be F.[[AlreadyCalled]].
- If alreadyCalled.[[Value]] is
true , returnundefined . Set alreadyCalled.[[Value]] totrue .- Let index be F.[[Index]].
- Let values be F.[[Values]].
- Let promiseCapability be F.[[Capability]].
- Let remainingElementsCount be F.[[RemainingElements]].
- Let obj be !
OrdinaryObjectCreate (%Object.prototype% ). - Perform !
CreateDataPropertyOrThrow (obj,"status" ,"rejected" ). - Perform !
CreateDataPropertyOrThrow (obj,"reason" , x). Set values[index] to obj.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let valuesArray be !
CreateArrayFromList (values). - Return ?
Call (promiseCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be !
- Return
undefined .
The Promise.allSettled reject element function is
27.2.4.3 Promise.any ( iterable )
The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError holding the rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
- Let C be the
this value. - Let promiseCapability be ?
NewPromiseCapability (C). - Let promiseResolve be
GetPromiseResolve (C). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
GetIterator (iterable). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
PerformPromiseAny (iteratorRecord, C, promiseCapability, promiseResolve). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toIteratorClose (iteratorRecord, result). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return
Completion (result).
The any function requires its Promise
27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseAny takes arguments iteratorRecord, constructor, resultCapability (a
Assert : !IsConstructor (constructor) istrue .Assert : !IsCallable (promiseResolve) istrue .- Let errors be a new empty
List . - Let remainingElementsCount be the
Record { [[Value]]: 1 }. - Let index be 0.
- Repeat,
- Let next be
IteratorStep (iteratorRecord). - If next is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (next).- If next is
false , thenSet iteratorRecord.[[Done]] totrue .Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let error be a newly created
AggregateErrorobject. - Perform !
DefinePropertyOrThrow (error,"errors" , PropertyDescriptor { [[Configurable]]:true , [[Enumerable]]:false , [[Writable]]:true , [[Value]]: !CreateArrayFromList (errors) }). - Return
ThrowCompletion (error).
- Let error be a newly created
- Return resultCapability.[[Promise]].
- Let nextValue be
IteratorValue (next). - If nextValue is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (nextValue).- Append
undefined to errors. - Let nextPromise be ?
Call (promiseResolve, constructor, « nextValue »). - Let stepsRejected be the algorithm steps defined in
.Promise.anyReject Element Functions - Let lengthRejected be the number of non-optional parameters of the function definition in
.Promise.anyReject Element Functions - Let onRejected be !
CreateBuiltinFunction (stepsRejected, lengthRejected,"" , « [[AlreadyCalled]], [[Index]], [[Errors]], [[Capability]], [[RemainingElements]] »). Set onRejected.[[AlreadyCalled]] tofalse .Set onRejected.[[Index]] to index.Set onRejected.[[Errors]] to errors.Set onRejected.[[Capability]] to resultCapability.Set onRejected.[[RemainingElements]] to remainingElementsCount.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.- Perform ?
Invoke (nextPromise,"then" , « resultCapability.[[Resolve]], onRejected »). Set index to index + 1.
- Let next be
27.2.4.3.2 Promise.any Reject Element Functions
A Promise.any reject element function is an anonymous built-in function that is used to reject a specific Promise.any element. Each Promise.any reject element function has [[Index]], [[Errors]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.
When a Promise.any reject element function is called with argument x, the following steps are taken:
- Let F be the
active function object . - If F.[[AlreadyCalled]] is
true , returnundefined . Set F.[[AlreadyCalled]] totrue .- Let index be F.[[Index]].
- Let errors be F.[[Errors]].
- Let promiseCapability be F.[[Capability]].
- Let remainingElementsCount be F.[[RemainingElements]].
Set errors[index] to x.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.- If remainingElementsCount.[[Value]] is 0, then
- Let error be a newly created
AggregateErrorobject. - Perform !
DefinePropertyOrThrow (error,"errors" , PropertyDescriptor { [[Configurable]]:true , [[Enumerable]]:false , [[Writable]]:true , [[Value]]: !CreateArrayFromList (errors) }). - Return ?
Call (promiseCapability.[[Reject]],undefined , « error »).
- Let error be a newly created
- Return
undefined .
The Promise.any reject element function is
27.2.4.4 Promise.prototype
The initial value of Promise.prototype is the
This property has the attributes { [[Writable]]:
27.2.4.5 Promise.race ( iterable )
The race function returns a new promise which is settled in the same way as the first passed promise to settle. It resolves all elements of the passed iterable to promises as it runs this algorithm.
- Let C be the
this value. - Let promiseCapability be ?
NewPromiseCapability (C). - Let promiseResolve be
GetPromiseResolve (C). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
GetIterator (iterable). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
PerformPromiseRace (iteratorRecord, C, promiseCapability, promiseResolve). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toIteratorClose (iteratorRecord, result). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return
Completion (result).
If the iterable argument is empty or if none of the promises in iterable ever settle then the pending promise returned by this method will never be settled.
The race function expects its resolve method.
27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseRace takes arguments iteratorRecord, constructor, resultCapability (a
Assert :IsConstructor (constructor) istrue .Assert :IsCallable (promiseResolve) istrue .- Repeat,
- Let next be
IteratorStep (iteratorRecord). - If next is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (next).- If next is
false , thenSet iteratorRecord.[[Done]] totrue .- Return resultCapability.[[Promise]].
- Let nextValue be
IteratorValue (next). - If nextValue is an
abrupt completion , set iteratorRecord.[[Done]] totrue . ReturnIfAbrupt (nextValue).- Let nextPromise be ?
Call (promiseResolve, constructor, « nextValue »). - Perform ?
Invoke (nextPromise,"then" , « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
- Let next be
27.2.4.6 Promise.reject ( r )
The reject function returns a new promise rejected with the passed argument.
- Let C be the
this value. - Let promiseCapability be ?
NewPromiseCapability (C). - Perform ?
Call (promiseCapability.[[Reject]],undefined , « r »). - Return promiseCapability.[[Promise]].
The reject function expects its
27.2.4.7 Promise.resolve ( x )
The resolve function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this
- Let C be the
this value. - If
Type (C) is not Object, throw aTypeError exception. - Return ?
PromiseResolve (C, x).
The resolve function expects its
27.2.4.7.1 PromiseResolve ( C, x )
The abstract operation PromiseResolve takes arguments C (a
27.2.4.8 get Promise [ @@species ]
Promise[@@species] is an
- Return the
this value.
The value of the
Promise prototype methods normally use their
27.2.5 Properties of the Promise Prototype Object
The Promise prototype object:
- is
%Promise.prototype% . - has a [[Prototype]] internal slot whose value is
%Object.prototype% . - is an
ordinary object . - does not have a [[PromiseState]] internal slot or any of the other internal slots of Promise instances.
27.2.5.1 Promise.prototype.catch ( onRejected )
When the catch method is called with argument onRejected, the following steps are taken:
- Let promise be the
this value. - Return ?
Invoke (promise,"then" , «undefined , onRejected »).
27.2.5.2 Promise.prototype.constructor
The initial value of Promise.prototype.constructor is
27.2.5.3 Promise.prototype.finally ( onFinally )
When the finally method is called with argument onFinally, the following steps are taken:
- Let promise be the
this value. - If
Type (promise) is not Object, throw aTypeError exception. - Let C be ?
SpeciesConstructor (promise,%Promise% ). Assert :IsConstructor (C) istrue .- If
IsCallable (onFinally) isfalse , then- Let thenFinally be onFinally.
- Let catchFinally be onFinally.
- Else,
- Let stepsThenFinally be the algorithm steps defined in
Then Finally Functions . - Let lengthThenFinally be the number of non-optional parameters of the function definition in
Then Finally Functions . - Let thenFinally be !
CreateBuiltinFunction (stepsThenFinally, lengthThenFinally,"" , « [[Constructor]], [[OnFinally]] »). Set thenFinally.[[Constructor]] to C.Set thenFinally.[[OnFinally]] to onFinally.- Let stepsCatchFinally be the algorithm steps defined in
Catch Finally Functions . - Let lengthCatchFinally be the number of non-optional parameters of the function definition in
Catch Finally Functions . - Let catchFinally be !
CreateBuiltinFunction (stepsCatchFinally, lengthCatchFinally,"" , « [[Constructor]], [[OnFinally]] »). Set catchFinally.[[Constructor]] to C.Set catchFinally.[[OnFinally]] to onFinally.
- Let stepsThenFinally be the algorithm steps defined in
- Return ?
Invoke (promise,"then" , « thenFinally, catchFinally »).
27.2.5.3.1 Then Finally Functions
A Then Finally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a Promise-like
When a Then Finally function is called with argument value, the following steps are taken:
- Let F be the
active function object . - Let onFinally be F.[[OnFinally]].
Assert :IsCallable (onFinally) istrue .- Let result be ?
Call (onFinally,undefined ). - Let C be F.[[Constructor]].
Assert :IsConstructor (C) istrue .- Let promise be ?
PromiseResolve (C, result). - Let valueThunk be equivalent to a function that returns value.
- Return ?
Invoke (promise,"then" , « valueThunk »).
The
27.2.5.3.2 Catch Finally Functions
A Catch Finally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a Promise-like
When a Catch Finally function is called with argument reason, the following steps are taken:
- Let F be the
active function object . - Let onFinally be F.[[OnFinally]].
Assert :IsCallable (onFinally) istrue .- Let result be ?
Call (onFinally,undefined ). - Let C be F.[[Constructor]].
Assert :IsConstructor (C) istrue .- Let promise be ?
PromiseResolve (C, result). - Let thrower be equivalent to a function that throws reason.
- Return ?
Invoke (promise,"then" , « thrower »).
The
27.2.5.4 Promise.prototype.then ( onFulfilled, onRejected )
When the then method is called with arguments onFulfilled and onRejected, the following steps are taken:
- Let promise be the
this value. - If
IsPromise (promise) isfalse , throw aTypeError exception. - Let C be ?
SpeciesConstructor (promise,%Promise% ). - Let resultCapability be ?
NewPromiseCapability (C). - Return
PerformPromiseThen (promise, onFulfilled, onRejected, resultCapability).
27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] )
The abstract operation PerformPromiseThen takes arguments promise, onFulfilled, and onRejected and optional argument resultCapability (a
Assert :IsPromise (promise) istrue .- If resultCapability is not present, then
Set resultCapability toundefined .
- If
IsCallable (onFulfilled) isfalse , then- Let onFulfilledJobCallback be
empty .
- Let onFulfilledJobCallback be
- Else,
- Let onFulfilledJobCallback be
HostMakeJobCallback (onFulfilled).
- Let onFulfilledJobCallback be
- If
IsCallable (onRejected) isfalse , then- Let onRejectedJobCallback be
empty .
- Let onRejectedJobCallback be
- Else,
- Let onRejectedJobCallback be
HostMakeJobCallback (onRejected).
- Let onRejectedJobCallback be
- Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]:
Fulfill , [[Handler]]: onFulfilledJobCallback }. - Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]:
Reject , [[Handler]]: onRejectedJobCallback }. - If promise.[[PromiseState]] is
pending , then - Else if promise.[[PromiseState]] is
fulfilled , then- Let value be promise.[[PromiseResult]].
- Let fulfillJob be
NewPromiseReactionJob (fulfillReaction, value). - Perform
HostEnqueuePromiseJob (fulfillJob.[[Job]], fulfillJob.[[Realm]]).
- Else,
Assert : The value of promise.[[PromiseState]] isrejected .- Let reason be promise.[[PromiseResult]].
- If promise.[[PromiseIsHandled]] is
false , performHostPromiseRejectionTracker (promise,"handle" ). - Let rejectJob be
NewPromiseReactionJob (rejectReaction, reason). - Perform
HostEnqueuePromiseJob (rejectJob.[[Job]], rejectJob.[[Realm]]).
Set promise.[[PromiseIsHandled]] totrue .- If resultCapability is
undefined , then- Return
undefined .
- Return
- Else,
- Return resultCapability.[[Promise]].
27.2.5.5 Promise.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
27.2.6 Properties of Promise Instances
Promise instances are ordinary objects that inherit properties from the
| Internal Slot | Description |
|---|---|
| [[PromiseState]] |
One of then method.
|
| [[PromiseResult]] |
The value with which the promise has been fulfilled or rejected, if any. Only meaningful if [[PromiseState]] is not |
| [[PromiseFulfillReactions]] |
A |
| [[PromiseRejectReactions]] |
A |
| [[PromiseIsHandled]] | A boolean indicating whether the promise has ever had a fulfillment or rejection handler; used in unhandled rejection tracking. |
27.3 GeneratorFunction Objects
GeneratorFunction objects are functions that are usually created by evaluating
27.3.1 The GeneratorFunction Constructor
The GeneratorFunction
- is
%GeneratorFunction% . - is a subclass of
Function. - creates and initializes a new GeneratorFunction object when called as a function rather than as a
constructor . Thus the function callGeneratorFunction (…)is equivalent to the object creation expressionnew GeneratorFunction (…)with the same arguments. - is designed to be subclassable. It may be used as the value of an
extendsclause of a class definition. Subclass constructors that intend to inherit the specified GeneratorFunction behaviour must include asupercall to the GeneratorFunctionconstructor to create and initialize subclass instances with the internal slots necessary for built-in GeneratorFunction behaviour. All ECMAScript syntactic forms for defining generator function objects create direct instances of GeneratorFunction. There is no syntactic means to create instances of GeneratorFunction subclasses.
27.3.1.1 GeneratorFunction ( p1, p2, … , pn, body )
The last argument specifies the body (executable code) of a generator function; any preceding arguments specify formal parameters.
When the GeneratorFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “p” arguments, and where body might also not be provided), the following steps are taken:
- Let C be the
active function object . - Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
- Return ?
CreateDynamicFunction (C, NewTarget,generator , args).
See NOTE for
27.3.2 Properties of the GeneratorFunction Constructor
The GeneratorFunction
- is a standard built-in
function object that inherits from the Functionconstructor . - has a [[Prototype]] internal slot whose value is
%Function% . - has a
"name" property whose value is"GeneratorFunction" . - has the following properties:
27.3.2.1 GeneratorFunction.length
This is a
27.3.2.2 GeneratorFunction.prototype
The initial value of GeneratorFunction.prototype is the
This property has the attributes { [[Writable]]:
27.3.3 Properties of the GeneratorFunction Prototype Object
The GeneratorFunction prototype object:
- is
%GeneratorFunction.prototype% (seeFigure 5 ). - is an
ordinary object . - is not a
function object and does not have an [[ECMAScriptCode]] internal slot or any other of the internal slots listed inTable 29 orTable 73 . - has a [[Prototype]] internal slot whose value is
%Function.prototype% .
27.3.3.1 GeneratorFunction.prototype.constructor
The initial value of GeneratorFunction.prototype.constructor is
This property has the attributes { [[Writable]]:
27.3.3.2 GeneratorFunction.prototype.prototype
The initial value of GeneratorFunction.prototype.prototype is the
This property has the attributes { [[Writable]]:
27.3.3.3 GeneratorFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
27.3.4 GeneratorFunction Instances
Every GeneratorFunction instance is an ECMAScript
Each GeneratorFunction instance has the following own properties:
27.3.4.1 length
The specification for the
27.3.4.2 name
The specification for the
27.3.4.3 prototype
Whenever a GeneratorFunction instance is created another
This property has the attributes { [[Writable]]:
Unlike Function instances, the object that is the value of the a GeneratorFunction's
27.4 AsyncGeneratorFunction Objects
AsyncGeneratorFunction objects are functions that are usually created by evaluating
27.4.1 The AsyncGeneratorFunction Constructor
The AsyncGeneratorFunction
- is
%AsyncGeneratorFunction% . - is a subclass of
Function. - creates and initializes a new AsyncGeneratorFunction object when called as a function rather than as a
constructor . Thus the function callAsyncGeneratorFunction (...)is equivalent to the object creation expressionnew AsyncGeneratorFunction (...)with the same arguments. - is designed to be subclassable. It may be used as the value of an
extendsclause of a class definition. Subclass constructors that intend to inherit the specified AsyncGeneratorFunction behaviour must include asupercall to the AsyncGeneratorFunctionconstructor to create and initialize subclass instances with the internal slots necessary for built-in AsyncGeneratorFunction behaviour. All ECMAScript syntactic forms for defining async generator function objects create direct instances of AsyncGeneratorFunction. There is no syntactic means to create instances of AsyncGeneratorFunction subclasses.
27.4.1.1 AsyncGeneratorFunction ( p1, p2, … , pn, body )
The last argument specifies the body (executable code) of an async generator function; any preceding arguments specify formal parameters.
When the AsyncGeneratorFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no "p" arguments, and where body might also not be provided), the following steps are taken:
- Let C be the
active function object . - Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
- Return ?
CreateDynamicFunction (C, NewTarget,asyncGenerator , args).
See NOTE for
27.4.2 Properties of the AsyncGeneratorFunction Constructor
The AsyncGeneratorFunction
- is a standard built-in
function object that inherits from the Functionconstructor . - has a [[Prototype]] internal slot whose value is
%Function% . - has a
"name" property whose value is"AsyncGeneratorFunction" . - has the following properties:
27.4.2.1 AsyncGeneratorFunction.length
This is a
27.4.2.2 AsyncGeneratorFunction.prototype
The initial value of AsyncGeneratorFunction.prototype is the
This property has the attributes { [[Writable]]:
27.4.3 Properties of the AsyncGeneratorFunction Prototype Object
The AsyncGeneratorFunction prototype object:
- is
%AsyncGeneratorFunction.prototype% . - is an
ordinary object . - is not a
function object and does not have an [[ECMAScriptCode]] internal slot or any other of the internal slots listed inTable 29 orTable 74 . - has a [[Prototype]] internal slot whose value is
%Function.prototype% .
27.4.3.1 AsyncGeneratorFunction.prototype.constructor
The initial value of AsyncGeneratorFunction.prototype.constructor is
This property has the attributes { [[Writable]]:
27.4.3.2 AsyncGeneratorFunction.prototype.prototype
The initial value of AsyncGeneratorFunction.prototype.prototype is the
This property has the attributes { [[Writable]]:
27.4.3.3 AsyncGeneratorFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
27.4.4 AsyncGeneratorFunction Instances
Every AsyncGeneratorFunction instance is an ECMAScript
Each AsyncGeneratorFunction instance has the following own properties:
27.4.4.1 length
The value of the
This property has the attributes { [[Writable]]:
27.4.4.2 name
The specification for the
27.4.4.3 prototype
Whenever an AsyncGeneratorFunction instance is created another
This property has the attributes { [[Writable]]:
Unlike function instances, the object that is the value of the an AsyncGeneratorFunction's
27.5 Generator Objects
A Generator object is an instance of a generator function and conforms to both the Iterator and Iterable interfaces.
Generator instances directly inherit properties from the object that is the initial value of the
27.5.1 Properties of the Generator Prototype Object
The Generator prototype object:
- is
%GeneratorFunction.prototype.prototype% . - is an
ordinary object . - is not a Generator instance and does not have a [[GeneratorState]] internal slot.
- has a [[Prototype]] internal slot whose value is
%IteratorPrototype% . - has properties that are indirectly inherited by all Generator instances.
27.5.1.1 Generator.prototype.constructor
The initial value of Generator.prototype.constructor is
This property has the attributes { [[Writable]]:
27.5.1.2 Generator.prototype.next ( value )
The next method performs the following steps:
- Let g be the
this value. - Return ?
GeneratorResume (g, value,empty ).
27.5.1.3 Generator.prototype.return ( value )
The return method performs the following steps:
- Let g be the
this value. - Let C be
Completion { [[Type]]:return , [[Value]]: value, [[Target]]:empty }. - Return ?
GeneratorResumeAbrupt (g, C,empty ).
27.5.1.4 Generator.prototype.throw ( exception )
The throw method performs the following steps:
- Let g be the
this value. - Let C be
ThrowCompletion (exception). - Return ?
GeneratorResumeAbrupt (g, C,empty ).
27.5.1.5 Generator.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
27.5.2 Properties of Generator Instances
Generator instances are initially created with the internal slots described in
| Internal Slot | Description |
|---|---|
| [[GeneratorState]] |
The current execution state of the generator. The possible values are: |
| [[GeneratorContext]] |
The |
| [[GeneratorBrand]] |
A brand used to distinguish different kinds of generators. The [[GeneratorBrand]] of generators declared by ECMAScript source text is always |
27.5.3 Generator Abstract Operations
27.5.3.1 GeneratorStart ( generator, generatorBody )
The abstract operation GeneratorStart takes arguments generator and generatorBody (a
Assert : The value of generator.[[GeneratorState]] isundefined .- Let genContext be the
running execution context . Set the Generator component of genContext to generator.Set the code evaluation state of genContext such that when evaluation is resumed for thatexecution context the following steps will be performed:- If generatorBody is a
Parse Node , then- Let result be the result of evaluating generatorBody.
- Else,
Assert : generatorBody is anAbstract Closure with no parameters.- Let result be generatorBody().
Assert : If we return here, the generator either threw an exception or performed either an implicit or explicit return.- Remove genContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . Set generator.[[GeneratorState]] tocompleted .- Once a generator enters the
completed state it never leaves it and its associatedexecution context is never resumed. Any execution state associated with generator can be discarded at this point. - If result.[[Type]] is
normal , let resultValue beundefined . - Else if result.[[Type]] is
return , let resultValue be result.[[Value]]. - Else,
Assert : result.[[Type]] isthrow .- Return
Completion (result).
- Return
CreateIterResultObject (resultValue,true ).
- If generatorBody is a
Set generator.[[GeneratorContext]] to genContext.Set generator.[[GeneratorState]] tosuspendedStart .- Return
NormalCompletion (undefined ).
27.5.3.2 GeneratorValidate ( generator, generatorBrand )
The abstract operation GeneratorValidate takes arguments generator and generatorBrand. It performs the following steps when called:
- Perform ?
RequireInternalSlot (generator, [[GeneratorState]]). - Perform ?
RequireInternalSlot (generator, [[GeneratorBrand]]). - If generator.[[GeneratorBrand]] is not the same value as generatorBrand, throw a
TypeError exception. Assert : generator also has a [[GeneratorContext]] internal slot.- Let state be generator.[[GeneratorState]].
- If state is
executing , throw aTypeError exception. - Return state.
27.5.3.3 GeneratorResume ( generator, value, generatorBrand )
The abstract operation GeneratorResume takes arguments generator, value, and generatorBrand. It performs the following steps when called:
- Let state be ?
GeneratorValidate (generator, generatorBrand). - If state is
completed , returnCreateIterResultObject (undefined ,true ). Assert : state is eithersuspendedStart orsuspendedYield .- Let genContext be generator.[[GeneratorContext]].
- Let methodContext be the
running execution context . - Suspend methodContext.
Set generator.[[GeneratorState]] toexecuting .- Push genContext onto the
execution context stack ; genContext is now therunning execution context . - Resume the suspended evaluation of genContext using
NormalCompletion (value) as the result of the operation that suspended it. Let result be the value returned by the resumed computation. Assert : When we return here, genContext has already been removed from theexecution context stack and methodContext is the currentlyrunning execution context .- Return
Completion (result).
27.5.3.4 GeneratorResumeAbrupt ( generator, abruptCompletion, generatorBrand )
The abstract operation GeneratorResumeAbrupt takes arguments generator, abruptCompletion (a
- Let state be ?
GeneratorValidate (generator, generatorBrand). - If state is
suspendedStart , thenSet generator.[[GeneratorState]] tocompleted .- Once a generator enters the
completed state it never leaves it and its associatedexecution context is never resumed. Any execution state associated with generator can be discarded at this point. Set state tocompleted .
- If state is
completed , then- If abruptCompletion.[[Type]] is
return , then- Return
CreateIterResultObject (abruptCompletion.[[Value]],true ).
- Return
- Return
Completion (abruptCompletion).
- If abruptCompletion.[[Type]] is
Assert : state issuspendedYield .- Let genContext be generator.[[GeneratorContext]].
- Let methodContext be the
running execution context . - Suspend methodContext.
Set generator.[[GeneratorState]] toexecuting .- Push genContext onto the
execution context stack ; genContext is now therunning execution context . - Resume the suspended evaluation of genContext using abruptCompletion as the result of the operation that suspended it. Let result be the completion record returned by the resumed computation.
Assert : When we return here, genContext has already been removed from theexecution context stack and methodContext is the currentlyrunning execution context .- Return
Completion (result).
27.5.3.5 GetGeneratorKind ( )
The abstract operation GetGeneratorKind takes no arguments. It performs the following steps when called:
- Let genContext be the
running execution context . - If genContext does not have a Generator component, return
non-generator . - Let generator be the Generator component of genContext.
- If generator has an [[AsyncGeneratorState]] internal slot, return
async . - Else, return
sync .
27.5.3.6 GeneratorYield ( iterNextObj )
The abstract operation GeneratorYield takes argument iterNextObj. It performs the following steps when called:
Assert : iterNextObj is an Object that implements the IteratorResult interface.- Let genContext be the
running execution context . Assert : genContext is theexecution context of a generator.- Let generator be the value of the Generator component of genContext.
Assert :GetGeneratorKind () issync .Set generator.[[GeneratorState]] tosuspendedYield .- Remove genContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . Set the code evaluation state of genContext such that when evaluation is resumed with aCompletion resumptionValue the following steps will be performed:- Return resumptionValue.
- NOTE: This returns to the evaluation of the
YieldExpression that originally called this abstract operation.
- Return
NormalCompletion (iterNextObj). - NOTE: This returns to the evaluation of the operation that had most previously resumed evaluation of genContext.
27.5.3.7 Yield ( value )
The abstract operation Yield takes argument value (an
- Let generatorKind be !
GetGeneratorKind (). - If generatorKind is
async , return ?AsyncGeneratorYield (value). - Otherwise, return ?
GeneratorYield (!CreateIterResultObject (value,false )).
27.5.3.8 CreateIteratorFromClosure ( closure, generatorBrand, generatorPrototype )
The abstract operation CreateIteratorFromClosure takes arguments closure (an
- NOTE: closure can contain uses of the
Yield shorthand to yield an IteratorResult object. - Let internalSlotsList be « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] ».
- Let generator be !
OrdinaryObjectCreate (generatorPrototype, internalSlotsList). Set generator.[[GeneratorBrand]] to generatorBrand.Set generator.[[GeneratorState]] toundefined .- Perform !
GeneratorStart (generator, closure). - Return generator.
27.6 AsyncGenerator Objects
An AsyncGenerator object is an instance of an async generator function and conforms to both the AsyncIterator and AsyncIterable interfaces.
AsyncGenerator instances directly inherit properties from the object that is the initial value of the
27.6.1 Properties of the AsyncGenerator Prototype Object
The AsyncGenerator prototype object:
- is
%AsyncGeneratorFunction.prototype.prototype% . - is an
ordinary object . - is not an AsyncGenerator instance and does not have an [[AsyncGeneratorState]] internal slot.
- has a [[Prototype]] internal slot whose value is
%AsyncIteratorPrototype% . - has properties that are indirectly inherited by all AsyncGenerator instances.
27.6.1.1 AsyncGenerator.prototype.constructor
The initial value of AsyncGenerator.prototype.constructor is
This property has the attributes { [[Writable]]:
27.6.1.2 AsyncGenerator.prototype.next ( value )
- Let generator be the
this value. - Let completion be
NormalCompletion (value). - Return !
AsyncGeneratorEnqueue (generator, completion,empty ).
27.6.1.3 AsyncGenerator.prototype.return ( value )
- Let generator be the
this value. - Let completion be
Completion { [[Type]]:return , [[Value]]: value, [[Target]]:empty }. - Return !
AsyncGeneratorEnqueue (generator, completion,empty ).
27.6.1.4 AsyncGenerator.prototype.throw ( exception )
- Let generator be the
this value. - Let completion be
ThrowCompletion (exception). - Return !
AsyncGeneratorEnqueue (generator, completion,empty ).
27.6.1.5 AsyncGenerator.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
27.6.2 Properties of AsyncGenerator Instances
AsyncGenerator instances are initially created with the internal slots described below:
| Internal Slot | Description |
|---|---|
| [[AsyncGeneratorState]] | The current execution state of the async generator. The possible values are: |
| [[AsyncGeneratorContext]] | The |
| [[AsyncGeneratorQueue]] | A |
| [[GeneratorBrand]] | A brand used to distinguish different kinds of async generators. The [[GeneratorBrand]] of async generators declared by ECMAScript source text is always |
27.6.3 AsyncGenerator Abstract Operations
27.6.3.1 AsyncGeneratorRequest Records
The AsyncGeneratorRequest is a
They have the following fields:
| Field Name | Value | Meaning |
|---|---|---|
| [[Completion]] | A |
The completion which should be used to resume the async generator. |
| [[Capability]] | A |
The promise capabilities associated with this request. |
27.6.3.2 AsyncGeneratorStart ( generator, generatorBody )
The abstract operation AsyncGeneratorStart takes arguments generator and generatorBody (a
Assert : generator is an AsyncGenerator instance.Assert : generator.[[AsyncGeneratorState]] isundefined .- Let genContext be the
running execution context . Set the Generator component of genContext to generator.Set the code evaluation state of genContext such that when evaluation is resumed for thatexecution context the following steps will be performed:- If generatorBody is a
Parse Node , then- Let result be the result of evaluating generatorBody.
- Else,
Assert : generatorBody is anAbstract Closure with no parameters.- Let result be generatorBody().
Assert : If we return here, the async generator either threw an exception or performed either an implicit or explicit return.- Remove genContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . Set generator.[[AsyncGeneratorState]] tocompleted .- If result is a normal completion, let resultValue be
undefined . - Else,
- Let resultValue be result.[[Value]].
- If result.[[Type]] is not
return , then- Return !
AsyncGeneratorReject (generator, resultValue).
- Return !
- Return !
AsyncGeneratorResolve (generator, resultValue,true ).
- If generatorBody is a
Set generator.[[AsyncGeneratorContext]] to genContext.Set generator.[[AsyncGeneratorState]] tosuspendedStart .Set generator.[[AsyncGeneratorQueue]] to a new emptyList .- Return
undefined .
27.6.3.3 AsyncGeneratorValidate ( generator, generatorBrand )
The abstract operation AsyncGeneratorValidate takes arguments generator and generatorBrand. It performs the following steps when called:
- Perform ?
RequireInternalSlot (generator, [[AsyncGeneratorContext]]). - Perform ?
RequireInternalSlot (generator, [[AsyncGeneratorState]]). - Perform ?
RequireInternalSlot (generator, [[AsyncGeneratorQueue]]). - If generator.[[GeneratorBrand]] is not the same value as generatorBrand, throw a
TypeError exception.
27.6.3.4 AsyncGeneratorResolve ( generator, value, done )
The abstract operation AsyncGeneratorResolve takes arguments generator, value, and done (a Boolean). It performs the following steps when called:
Assert : generator is an AsyncGenerator instance.- Let queue be generator.[[AsyncGeneratorQueue]].
Assert : queue is not an emptyList .- Let next be the first element of queue.
- Remove the first element from queue.
- Let promiseCapability be next.[[Capability]].
- Let iteratorResult be !
CreateIterResultObject (value, done). - Perform !
Call (promiseCapability.[[Resolve]],undefined , « iteratorResult »). - Perform !
AsyncGeneratorResumeNext (generator). - Return
undefined .
27.6.3.5 AsyncGeneratorReject ( generator, exception )
The abstract operation AsyncGeneratorReject takes arguments generator and exception. It performs the following steps when called:
Assert : generator is an AsyncGenerator instance.- Let queue be generator.[[AsyncGeneratorQueue]].
Assert : queue is not an emptyList .- Let next be the first element of queue.
- Remove the first element from queue.
- Let promiseCapability be next.[[Capability]].
- Perform !
Call (promiseCapability.[[Reject]],undefined , « exception »). - Perform !
AsyncGeneratorResumeNext (generator). - Return
undefined .
27.6.3.6 AsyncGeneratorResumeNext ( generator )
The abstract operation AsyncGeneratorResumeNext takes argument generator. It performs the following steps when called:
Assert : generator is an AsyncGenerator instance.- Let state be generator.[[AsyncGeneratorState]].
Assert : state is notexecuting .- If state is
awaiting-return , returnundefined . - Let queue be generator.[[AsyncGeneratorQueue]].
- If queue is an empty
List , returnundefined . - Let next be the value of the first element of queue.
Assert : next is an AsyncGeneratorRequest record.- Let completion be next.[[Completion]].
- If completion is an
abrupt completion , then- If state is
suspendedStart , then - If state is
completed , then- If completion.[[Type]] is
return , thenSet generator.[[AsyncGeneratorState]] toawaiting-return .- Let promise be ?
PromiseResolve (%Promise% , completion.[[Value]]). - Let stepsFulfilled be the algorithm steps defined in
AsyncGeneratorResumeNext Return Processor Fulfilled Functions . - Let lengthFulfilled be the number of non-optional parameters of the function definition in
AsyncGeneratorResumeNext Return Processor Fulfilled Functions . - Let onFulfilled be !
CreateBuiltinFunction (stepsFulfilled, lengthFulfilled,"" , « [[Generator]] »). Set onFulfilled.[[Generator]] to generator.- Let stepsRejected be the algorithm steps defined in
AsyncGeneratorResumeNext Return Processor Rejected Functions . - Let lengthRejected be the number of non-optional parameters of the function definition in
AsyncGeneratorResumeNext Return Processor Rejected Functions . - Let onRejected be !
CreateBuiltinFunction (stepsRejected, lengthRejected,"" , « [[Generator]] »). Set onRejected.[[Generator]] to generator.- Perform !
PerformPromiseThen (promise, onFulfilled, onRejected). - Return
undefined .
- Else,
Assert : completion.[[Type]] isthrow .- Perform !
AsyncGeneratorReject (generator, completion.[[Value]]). - Return
undefined .
- If completion.[[Type]] is
- If state is
- Else if state is
completed , return !AsyncGeneratorResolve (generator,undefined ,true ). Assert : state is eithersuspendedStart orsuspendedYield .- Let genContext be generator.[[AsyncGeneratorContext]].
- Let callerContext be the
running execution context . - Suspend callerContext.
Set generator.[[AsyncGeneratorState]] toexecuting .- Push genContext onto the
execution context stack ; genContext is now therunning execution context . - Resume the suspended evaluation of genContext using completion as the result of the operation that suspended it. Let result be the completion record returned by the resumed computation.
Assert : result is never anabrupt completion .Assert : When we return here, genContext has already been removed from theexecution context stack and callerContext is the currentlyrunning execution context .- Return
undefined .
27.6.3.6.1 AsyncGeneratorResumeNext Return Processor Fulfilled Functions
An
When an
- Let F be the
active function object . Set F.[[Generator]].[[AsyncGeneratorState]] tocompleted .- Return !
AsyncGeneratorResolve (F.[[Generator]], value,true ).
The
27.6.3.6.2 AsyncGeneratorResumeNext Return Processor Rejected Functions
An
When an
- Let F be the
active function object . Set F.[[Generator]].[[AsyncGeneratorState]] tocompleted .- Return !
AsyncGeneratorReject (F.[[Generator]], reason).
The
27.6.3.7 AsyncGeneratorEnqueue ( generator, completion, generatorBrand )
The abstract operation AsyncGeneratorEnqueue takes arguments generator, completion (a
- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let check be
AsyncGeneratorValidate (generator, generatorBrand). - If check is an
abrupt completion , then- Let badGeneratorError be a newly created
TypeError object. - Perform !
Call (promiseCapability.[[Reject]],undefined , « badGeneratorError »). - Return promiseCapability.[[Promise]].
- Let badGeneratorError be a newly created
- Let queue be generator.[[AsyncGeneratorQueue]].
- Let request be AsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }.
- Append request to the end of queue.
- Let state be generator.[[AsyncGeneratorState]].
- If state is not
executing , then- Perform !
AsyncGeneratorResumeNext (generator).
- Perform !
- Return promiseCapability.[[Promise]].
27.6.3.8 AsyncGeneratorYield ( value )
The abstract operation AsyncGeneratorYield takes argument value. It performs the following steps when called:
- Let genContext be the
running execution context . Assert : genContext is theexecution context of a generator.- Let generator be the value of the Generator component of genContext.
Assert :GetGeneratorKind () isasync .Set value to ?Await (value).Set generator.[[AsyncGeneratorState]] tosuspendedYield .- Remove genContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . Set the code evaluation state of genContext such that when evaluation is resumed with aCompletion resumptionValue the following steps will be performed:- If resumptionValue.[[Type]] is not
return , returnCompletion (resumptionValue). - Let awaited be
Await (resumptionValue.[[Value]]). - If awaited.[[Type]] is
throw , returnCompletion (awaited). Assert : awaited.[[Type]] isnormal .- Return
Completion { [[Type]]:return , [[Value]]: awaited.[[Value]], [[Target]]:empty }. - NOTE: When one of the above steps returns, it returns to the evaluation of the
YieldExpression production that originally called this abstract operation.
- If resumptionValue.[[Type]] is not
- Return !
AsyncGeneratorResolve (generator, value,false ). - NOTE: This returns to the evaluation of the operation that had most previously resumed evaluation of genContext.
27.6.3.9 CreateAsyncIteratorFromClosure ( closure, generatorBrand, generatorPrototype )
The abstract operation CreateAsyncIteratorFromClosure takes arguments closure (an
- NOTE: closure can contain uses of the
Await shorthand and uses of theYield shorthand to yield an IteratorResult object. - Let internalSlotsList be « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] ».
- Let generator be !
OrdinaryObjectCreate (generatorPrototype, internalSlotsList). Set generator.[[GeneratorBrand]] to generatorBrand.Set generator.[[AsyncGeneratorState]] toundefined .- Perform !
AsyncGeneratorStart (generator, closure). - Return generator.
27.7 AsyncFunction Objects
AsyncFunction objects are functions that are usually created by evaluating
27.7.1 The AsyncFunction Constructor
The AsyncFunction
- is
%AsyncFunction% . - is a subclass of
Function. - creates and initializes a new AsyncFunction object when called as a function rather than as a
constructor . Thus the function callAsyncFunction(…)is equivalent to the object creation expressionnew AsyncFunction(…)with the same arguments. - is designed to be subclassable. It may be used as the value of an
extendsclause of a class definition. Subclass constructors that intend to inherit the specified AsyncFunction behaviour must include asupercall to the AsyncFunctionconstructor to create and initialize a subclass instance with the internal slots necessary for built-in async function behaviour. All ECMAScript syntactic forms for defining async function objects create direct instances of AsyncFunction. There is no syntactic means to create instances of AsyncFunction subclasses.
27.7.1.1 AsyncFunction ( p1, p2, … , pn, body )
The last argument specifies the body (executable code) of an async function. Any preceding arguments specify formal parameters.
When the AsyncFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no p arguments, and where body might also not be provided), the following steps are taken:
- Let C be the
active function object . - Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
- Return
CreateDynamicFunction (C, NewTarget,async , args).
27.7.2 Properties of the AsyncFunction Constructor
The AsyncFunction
- is a standard built-in
function object that inherits from the Functionconstructor . - has a [[Prototype]] internal slot whose value is
%Function% . - has a
"name" property whose value is"AsyncFunction" . - has the following properties:
27.7.2.1 AsyncFunction.length
This is a
27.7.2.2 AsyncFunction.prototype
The initial value of AsyncFunction.prototype is the
This property has the attributes { [[Writable]]:
27.7.3 Properties of the AsyncFunction Prototype Object
The AsyncFunction prototype object:
- is
%AsyncFunction.prototype% . - is an
ordinary object . - is not a
function object and does not have an [[ECMAScriptCode]] internal slot or any other of the internal slots listed inTable 29 . - has a [[Prototype]] internal slot whose value is
%Function.prototype% .
27.7.3.1 AsyncFunction.prototype.constructor
The initial value of AsyncFunction.prototype.constructor is
This property has the attributes { [[Writable]]:
27.7.3.2 AsyncFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value
This property has the attributes { [[Writable]]:
27.7.4 AsyncFunction Instances
Every AsyncFunction instance is an ECMAScript
Each AsyncFunction instance has the following own properties:
27.7.4.1 length
The specification for the
27.7.4.2 name
The specification for the
27.7.5 Async Functions Abstract Operations
27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody )
The abstract operation AsyncFunctionStart takes arguments promiseCapability (a
- Let runningContext be the
running execution context . - Let asyncContext be a copy of runningContext.
- NOTE: Copying the execution state is required for the step below to resume its execution. It is ill-defined to resume a currently executing context.
Set the code evaluation state of asyncContext such that when evaluation is resumed for thatexecution context the following steps will be performed:- Let result be the result of evaluating asyncFunctionBody.
Assert : If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.- Remove asyncContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - If result.[[Type]] is
normal , then- Perform !
Call (promiseCapability.[[Resolve]],undefined , «undefined »).
- Perform !
- Else if result.[[Type]] is
return , then- Perform !
Call (promiseCapability.[[Resolve]],undefined , « result.[[Value]] »).
- Perform !
- Else,
- Return.
- Push asyncContext onto the
execution context stack ; asyncContext is now therunning execution context . - Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
Assert : When we return here, asyncContext has already been removed from theexecution context stack and runningContext is the currentlyrunning execution context .Assert : result is a normal completion with a value ofundefined . The possible sources of completion values areAwait or, if the async function doesn't await anything, step4.g above.- Return.