27 Control Abstraction Objects
27.1 Iteration
27.1.1 Common Iteration Interfaces
An interface is a set of
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 that 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 that 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 that 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 |
|---|---|---|
|
|
a Boolean |
This is the result status of an iterator next method call. If the end of the iterator was reached |
|
|
an |
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 ] ( )
This function performs the following steps when called:
- 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 ] ( )
This function performs the following steps when called:
- 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 (an
- Let asyncIterator be
OrdinaryObjectCreate (%AsyncFromSyncIteratorPrototype% , « [[SyncIteratorRecord]] »). - Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord.
- Let nextMethod be !
Get (asyncIterator,"next" ). - Let iteratorRecord be the
Iterator 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 : Ois an Object that has a [[SyncIteratorRecord]] internal slot.- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let syncIteratorRecord be O.[[SyncIteratorRecord]].
- If value is present, then
- Let result be
Completion (IteratorNext (syncIteratorRecord, value)).
- Let result be
- Else,
- Let result be
Completion (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 : Ois an Object that has a [[SyncIteratorRecord]] internal slot.- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
- Let return be
Completion (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
Completion (Call (return, syncIterator, « value »)).
- Let result be
- Else,
- Let result be
Completion (Call (return, syncIterator)).
- Let result be
IfAbruptRejectPromise (result, promiseCapability).- If result
is not an 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 : Ois an Object that has a [[SyncIteratorRecord]] internal slot.- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
- Let throw be
Completion (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
Completion (Call (throw, syncIterator, « value »)).
- Let result be
- Else,
- Let result be
Completion (Call (throw, syncIterator)).
- Let result be
IfAbruptRejectPromise (result, promiseCapability).- If result
is not an Object , then- Perform !
Call (promiseCapability.[[Reject]],undefined , « a newly createdTypeError object »). - Return promiseCapability.[[Promise]].
- Perform !
- Return
AsyncFromSyncIteratorContinuation (result, promiseCapability).
27.1.4.3 Properties of Async-from-Sync Iterator Instances
Async-from-Sync Iterator instances are
| Internal Slot | Type | Description |
|---|---|---|
| [[SyncIteratorRecord]] |
an |
Represents the original synchronous iterator which is being adapted. |
27.1.4.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability )
The abstract operation AsyncFromSyncIteratorContinuation takes arguments result (an Object) and promiseCapability (a
- NOTE: Because promiseCapability is derived from the intrinsic
%Promise% , the calls to promiseCapability.[[Reject]] entailed by the useIfAbruptRejectPromise below are guaranteed not to throw. - Let done be
Completion (IteratorComplete (result)). IfAbruptRejectPromise (done, promiseCapability).- Let value be
Completion (IteratorValue (result)). IfAbruptRejectPromise (value, promiseCapability).- Let valueWrapper be
Completion (PromiseResolve (%Promise% , value)). IfAbruptRejectPromise (valueWrapper, promiseCapability).- Let unwrap be a new
Abstract Closure with parameters (v) that captures done and performs the following steps when called:- Return
CreateIterResultObject (v, done).
- Return
- Let onFulfilled be
CreateBuiltinFunction (unwrap, 1,"" , « »). - NOTE: onFulfilled is used when processing the
"value" property of an IteratorResult object in order to wait for its value if it is a promise and re-package the result in a new "unwrapped" IteratorResult object. - 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 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. |
| [[Reject]] |
a |
The function that is used to reject the given promise. |
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:
Assert : value is aCompletion Record .- If value is an
abrupt completion , then- Perform ?
Call (capability.[[Reject]],undefined , « value.[[Value]] »). - Return capability.[[Promise]].
- Perform ?
- Else,
- Set value to ! value.
27.2.1.2 PromiseReaction Records
A PromiseReaction Record 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 (a Promise) and returns a
- 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 valueis an Object .- Let promise be F.[[Promise]].
- Let alreadyResolved be F.[[AlreadyResolved]].
- If alreadyResolved.[[Value]] is
true , returnundefined . - Set alreadyResolved.[[Value]] to
true . - Perform
RejectPromise (promise, reason). - Return
undefined .
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 valueis an Object .- Let promise be F.[[Promise]].
- Let alreadyResolved be F.[[AlreadyResolved]].
- If alreadyResolved.[[Value]] is
true , returnundefined . - Set alreadyResolved.[[Value]] to
true . - If
SameValue (resolution, promise) istrue , then- Let selfResolutionError be a newly created
TypeError object. - Perform
RejectPromise (promise, selfResolutionError). - Return
undefined .
- Let selfResolutionError be a newly created
- If resolution
is not an Object , then- Perform
FulfillPromise (promise, resolution). - Return
undefined .
- Perform
- Let then be
Completion (Get (resolution,"then" )). - If then is an
abrupt completion , then- Perform
RejectPromise (promise, then.[[Value]]). - Return
undefined .
- Perform
- Let thenAction be then.[[Value]].
- If
IsCallable (thenAction) isfalse , then- Perform
FulfillPromise (promise, resolution). - Return
undefined .
- Perform
- 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 (a Promise) and value (an
Assert : The value of promise.[[PromiseState]] ispending .- Let reactions be promise.[[PromiseFulfillReactions]].
- Set promise.[[PromiseResult]] to value.
- Set promise.[[PromiseFulfillReactions]] to
undefined . - Set promise.[[PromiseRejectReactions]] to
undefined . - Set promise.[[PromiseState]] to
fulfilled . - Perform
TriggerPromiseReactions (reactions, value). - Return
unused .
27.2.1.5 NewPromiseCapability ( C )
The abstract operation NewPromiseCapability takes argument C (an resolve and reject functions. The promise 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 resolvingFunctions be the
Record { [[Resolve]]:undefined , [[Reject]]:undefined }. - Let executorClosure be a new
Abstract Closure with parameters (resolve, reject) that captures resolvingFunctions and performs the following steps when called:- If resolvingFunctions.[[Resolve]] is not
undefined , throw aTypeError exception. - If resolvingFunctions.[[Reject]] is not
undefined , throw aTypeError exception. - Set resolvingFunctions.[[Resolve]] to resolve.
- Set resolvingFunctions.[[Reject]] to reject.
- Return
undefined .
- If resolvingFunctions.[[Resolve]] is not
- Let executor be
CreateBuiltinFunction (executorClosure, 2,"" , « »). - Let promise be ?
Construct (C, « executor »). - If
IsCallable (resolvingFunctions.[[Resolve]]) isfalse , throw aTypeError exception. - If
IsCallable (resolvingFunctions.[[Reject]]) isfalse , throw aTypeError exception. - Return the
PromiseCapability Record { [[Promise]]: promise, [[Resolve]]: resolvingFunctions.[[Resolve]], [[Reject]]: resolvingFunctions.[[Reject]] }.
This abstract operation supports Promise subclassing, as it is generic on any
27.2.1.6 IsPromise ( x )
The abstract operation IsPromise takes argument x (an
- If x
is not an 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 (a Promise) and reason (an
Assert : The value of promise.[[PromiseState]] ispending .- Let reactions be promise.[[PromiseRejectReactions]].
- Set promise.[[PromiseResult]] to reason.
- Set promise.[[PromiseFulfillReactions]] to
undefined . - Set promise.[[PromiseRejectReactions]] to
undefined . - Set promise.[[PromiseState]] to
rejected . - If promise.[[PromiseIsHandled]] is
false , performHostPromiseRejectionTracker (promise,"reject" ). - Perform
TriggerPromiseReactions (reactions, reason). - Return
unused .
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
unused .
27.2.1.9 HostPromiseRejectionTracker ( promise, operation )
The
The default implementation of HostPromiseRejectionTracker is to return
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 (a
- Let job be a new
Job Abstract Closure with no parameters that captures reaction and argument and performs the following steps when called:- Let promiseCapability be reaction.[[Capability]].
- Let type be reaction.[[Type]].
- Let handler be reaction.[[Handler]].
- If handler is
empty , then- If type is
fulfill , then- Let handlerResult be
NormalCompletion (argument).
- Let handlerResult be
- Else,
Assert : type isreject .- Let handlerResult be
ThrowCompletion (argument).
- If type is
- Else,
- Let handlerResult be
Completion (HostCallJobCallback (handler,undefined , « argument »)).
- Let handlerResult be
- If promiseCapability is
undefined , thenAssert : handlerResult is not anabrupt completion .- Return
empty .
Assert : promiseCapability is aPromiseCapability Record .- If handlerResult is an
abrupt completion , then- Return ?
Call (promiseCapability.[[Reject]],undefined , « handlerResult.[[Value]] »).
- Return ?
- Else,
- Return ?
Call (promiseCapability.[[Resolve]],undefined , « handlerResult.[[Value]] »).
- Return ?
- Let handlerRealm be
null . - If reaction.[[Handler]] is not
empty , then- Let getHandlerRealmResult be
Completion (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 (a Promise), thenable (an Object), and then (a
- 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
Completion (HostCallJobCallback (then, thenable, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »)). - If thenCallResult is an
abrupt completion , then- Return ?
Call (resolvingFunctions.[[Reject]],undefined , « thenCallResult.[[Value]] »).
- Return ?
- Return ? thenCallResult.
- Let resolvingFunctions be
- Let getThenRealmResult be
Completion (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 when called as a
constructor . - is not intended to be called as a function and will throw an exception when called in that manner.
- may be used as the value in an
extendsclause of a class definition. Subclassconstructors 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 )
This function performs the following steps when called:
- 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]] to
pending . - Set promise.[[PromiseFulfillReactions]] to a new empty
List . - Set promise.[[PromiseRejectReactions]] to a new empty
List . - Set promise.[[PromiseIsHandled]] to
false . - Let resolvingFunctions be
CreateResolvingFunctions (promise). - Let completion be
Completion (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. 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 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 )
This 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
Completion (GetPromiseResolve (C)). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
Completion (GetIterator (iterable,sync )). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
Completion (PerformPromiseAll (iteratorRecord, C, promiseCapability, promiseResolve)). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toCompletion (IteratorClose (iteratorRecord, result)). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return ? result.
This function requires its
27.2.4.1.1 GetPromiseResolve ( promiseConstructor )
The abstract operation GetPromiseResolve takes argument promiseConstructor (a
- 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 (an
- Let values be a new empty
List . - Let remainingElementsCount be the
Record { [[Value]]: 1 }. - Let index be 0.
- Repeat,
- Let next be ?
IteratorStepValue (iteratorRecord). - If next is
done , then- Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
- If remainingElementsCount.[[Value]] = 0, then
- Let valuesArray be
CreateArrayFromList (values). - Perform ?
Call (resultCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be
- Return resultCapability.[[Promise]].
- Append
undefined to values. - Let nextPromise be ?
Call (promiseResolve, constructor, « next »). - 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]] to
false . - 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]] to
true . - 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]] = 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 )
This 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
Completion (GetPromiseResolve (C)). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
Completion (GetIterator (iterable,sync )). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
Completion (PerformPromiseAllSettled (iteratorRecord, C, promiseCapability, promiseResolve)). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toCompletion (IteratorClose (iteratorRecord, result)). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return ? result.
This function requires its
27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord (an
- Let values be a new empty
List . - Let remainingElementsCount be the
Record { [[Value]]: 1 }. - Let index be 0.
- Repeat,
- Let next be ?
IteratorStepValue (iteratorRecord). - If next is
done , then- Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
- If remainingElementsCount.[[Value]] = 0, then
- Let valuesArray be
CreateArrayFromList (values). - Perform ?
Call (resultCapability.[[Resolve]],undefined , « valuesArray »).
- Let valuesArray be
- Return resultCapability.[[Promise]].
- Append
undefined to values. - Let nextPromise be ?
Call (promiseResolve, constructor, « next »). - 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]] to
true . - 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]] = 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]] to
true . - 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]] = 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 )
This 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
Completion (GetPromiseResolve (C)). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
Completion (GetIterator (iterable,sync )). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
Completion (PerformPromiseAny (iteratorRecord, C, promiseCapability, promiseResolve)). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toCompletion (IteratorClose (iteratorRecord, result)). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return ? result.
This function requires its Promise
27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseAny takes arguments iteratorRecord (an
- Let errors be a new empty
List . - Let remainingElementsCount be the
Record { [[Value]]: 1 }. - Let index be 0.
- Repeat,
- Let next be ?
IteratorStepValue (iteratorRecord). - If next is
done , then- Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
- If remainingElementsCount.[[Value]] = 0, then
- Let error be a newly created
AggregateError object. - 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]].
- Append
undefined to errors. - Let nextPromise be ?
Call (promiseResolve, constructor, « next »). - 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]] to
false . - 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]] to
true . - 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]] = 0, then
- Let error be a newly created
AggregateError object. - 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 )
This 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
Completion (GetPromiseResolve (C)). IfAbruptRejectPromise (promiseResolve, promiseCapability).- Let iteratorRecord be
Completion (GetIterator (iterable,sync )). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
Completion (PerformPromiseRace (iteratorRecord, C, promiseCapability, promiseResolve)). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , set result toCompletion (IteratorClose (iteratorRecord, result)). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return ? result.
If the iterable argument yields no values or if none of the promises yielded by iterable ever settle, then the pending promise returned by this method will never be settled.
This function expects its resolve method.
27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve )
The abstract operation PerformPromiseRace takes arguments iteratorRecord (an
- Repeat,
- Let next be ?
IteratorStepValue (iteratorRecord). - If next is
done , then- Return resultCapability.[[Promise]].
- Let nextPromise be ?
Call (promiseResolve, constructor, « next »). - Perform ?
Invoke (nextPromise,"then" , « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
- Let next be ?
27.2.4.6 Promise.reject ( r )
This 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]].
This function expects its
27.2.4.7 Promise.resolve ( x )
This 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 C
is not an Object , throw aTypeError exception. - Return ?
PromiseResolve (C, x).
This function expects its
27.2.4.7.1 PromiseResolve ( C, x )
The abstract operation PromiseResolve takes arguments C (a
- If
IsPromise (x) istrue , then - Let promiseCapability be ?
NewPromiseCapability (C). - Perform ?
Call (promiseCapability.[[Resolve]],undefined , « x »). - Return promiseCapability.[[Promise]].
27.2.4.8 Promise.withResolvers ( )
This function returns an object with three properties: a new promise together with the resolve and reject functions associated with it.
- Let C be the
this value. - Let promiseCapability be ?
NewPromiseCapability (C). - Let obj be
OrdinaryObjectCreate (%Object.prototype% ). - Perform !
CreateDataPropertyOrThrow (obj,"promise" , promiseCapability.[[Promise]]). - Perform !
CreateDataPropertyOrThrow (obj,"resolve" , promiseCapability.[[Resolve]]). - Perform !
CreateDataPropertyOrThrow (obj,"reject" , promiseCapability.[[Reject]]). - Return obj.
27.2.4.9 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 )
This method performs the following steps when called:
- 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 )
This method performs the following steps when called:
- Let promise be the
this value. - If promise
is not an 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 thenFinallyClosure be a new
Abstract Closure with parameters (value) that captures onFinally and C and performs the following steps when called:- Let result be ?
Call (onFinally,undefined ). - Let p be ?
PromiseResolve (C, result). - Let returnValue be a new
Abstract Closure with no parameters that captures value and performs the following steps when called:- Return value.
- Let valueThunk be
CreateBuiltinFunction (returnValue, 0,"" , « »). - Return ?
Invoke (p,"then" , « valueThunk »).
- Let result be ?
- Let thenFinally be
CreateBuiltinFunction (thenFinallyClosure, 1,"" , « »). - Let catchFinallyClosure be a new
Abstract Closure with parameters (reason) that captures onFinally and C and performs the following steps when called:- Let result be ?
Call (onFinally,undefined ). - Let p be ?
PromiseResolve (C, result). - Let throwReason be a new
Abstract Closure with no parameters that captures reason and performs the following steps when called:- Return
ThrowCompletion (reason).
- Return
- Let thrower be
CreateBuiltinFunction (throwReason, 0,"" , « »). - Return ?
Invoke (p,"then" , « thrower »).
- Let result be ?
- Let catchFinally be
CreateBuiltinFunction (catchFinallyClosure, 1,"" , « »).
- Let thenFinallyClosure be a new
- Return ?
Invoke (promise,"then" , « thenFinally, catchFinally »).
27.2.5.4 Promise.prototype.then ( onFulfilled, onRejected )
This method performs the following steps when called:
- 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 (a Promise), onFulfilled (an
Assert :IsPromise (promise) istrue .- If resultCapability is not present, then
- Set resultCapability to
undefined .
- Set resultCapability to
- 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 Record { [[Capability]]: resultCapability, [[Type]]:fulfill , [[Handler]]: onFulfilledJobCallback }. - Let rejectReaction be the
PromiseReaction Record { [[Capability]]: resultCapability, [[Type]]:reject , [[Handler]]: onRejectedJobCallback }. - If promise.[[PromiseState]] is
pending , then- Append fulfillReaction to promise.[[PromiseFulfillReactions]].
- Append rejectReaction to promise.[[PromiseRejectReactions]].
- 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]] to
true . - 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
| Internal Slot | Type | Description |
|---|---|---|
| [[PromiseState]] |
|
Governs how a promise will react to incoming calls to its then method.
|
| [[PromiseResult]] |
an |
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 | Indicates whether the promise has ever had a fulfillment or rejection handler; used in unhandled rejection tracking. |
27.3 GeneratorFunction Objects
GeneratorFunctions 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 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. - may be used as the value of an
extendsclause of a class definition. Subclassconstructors 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 generatorfunction objects create direct instances of GeneratorFunction. There is no syntactic means to create instances of GeneratorFunction subclasses.
27.3.1.1 GeneratorFunction ( ...parameterArgs, bodyArg )
The last argument (if any) specifies the body (executable code) of a generator function; any preceding arguments specify formal parameters.
This function performs the following steps when called:
- Let C be the
active function object . - If bodyArg is not present, set bodyArg to the empty String.
- Return ?
CreateDynamicFunction (C, NewTarget,generator , parameterArgs, bodyArg).
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
"length" property whose value is1 𝔽. - has a
"name" property whose value is"GeneratorFunction" . - has the following properties:
27.3.2.1 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 6 ). - 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 30 orTable 88 . - 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 a GeneratorFunction's
27.4 AsyncGeneratorFunction Objects
AsyncGeneratorFunctions 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 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. - may be used as the value of an
extendsclause of a class definition. Subclassconstructors 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 generatorfunction objects create direct instances of AsyncGeneratorFunction. There is no syntactic means to create instances of AsyncGeneratorFunction subclasses.
27.4.1.1 AsyncGeneratorFunction ( ...parameterArgs, bodyArg )
The last argument (if any) specifies the body (executable code) of an async generator function; any preceding arguments specify formal parameters.
This function performs the following steps when called:
- Let C be the
active function object . - If bodyArg is not present, set bodyArg to the empty String.
- Return ?
CreateDynamicFunction (C, NewTarget,async-generator , parameterArgs, bodyArg).
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
"length" property whose value is1 𝔽. - has a
"name" property whose value is"AsyncGeneratorFunction" . - has the following properties:
27.4.2.1 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 30 orTable 89 . - 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 an AsyncGeneratorFunction's
27.5 Generator Objects
A Generator 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 )
- Return ?
GeneratorResume (this value, value,empty ).
27.5.1.3 Generator.prototype.return ( value )
This method performs the following steps when called:
- Let g be the
this value. - Let C be
Completion Record { [[Type]]:return , [[Value]]: value, [[Target]]:empty }. - Return ?
GeneratorResumeAbrupt (g, C,empty ).
27.5.1.4 Generator.prototype.throw ( exception )
This method performs the following steps when called:
- 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 | Type | Description |
|---|---|---|
| [[GeneratorState]] |
|
The current execution state of the generator. |
| [[GeneratorContext]] |
an |
The |
| [[GeneratorBrand]] |
a String or |
A brand used to distinguish different kinds of generators. The [[GeneratorBrand]] of generators declared by |
27.5.3 Generator Abstract Operations
27.5.3.1 GeneratorStart ( generator, generatorBody )
The abstract operation GeneratorStart takes arguments generator (a 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.
- Let closure be a new
Abstract Closure with no parameters that captures generatorBody and performs the following steps when called:- Let acGenContext be the
running execution context . - Let acGenerator be the Generator component of acGenContext.
- If generatorBody is a
Parse Node , then- Let result be
Completion (Evaluation of generatorBody).
- Let result be
- 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 acGenContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - Set acGenerator.[[GeneratorState]] to
completed . - NOTE: Once a generator enters the
completed state it never leaves it and its associatedexecution context is never resumed. Any execution state associated with acGenerator can be discarded at this point. - If result is a
normal completion , then- Let resultValue be
undefined .
- Let resultValue be
- Else if result is a
return completion , then- Let resultValue be result.[[Value]].
- Else,
Assert : result is athrow completion .- Return ? result.
- Return
CreateIterResultObject (resultValue,true ).
- Let acGenContext be the
- Set the code evaluation state of genContext such that when evaluation is resumed for that
execution context , closure will be called with no arguments. - Set generator.[[GeneratorContext]] to genContext.
- Set generator.[[GeneratorState]] to
suspended-start . - Return
unused .
27.5.3.2 GeneratorValidate ( generator, generatorBrand )
The abstract operation GeneratorValidate takes arguments generator (an
- Perform ?
RequireInternalSlot (generator, [[GeneratorState]]). - Perform ?
RequireInternalSlot (generator, [[GeneratorBrand]]). - If generator.[[GeneratorBrand]] is not 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 (an
- Let state be ?
GeneratorValidate (generator, generatorBrand). - If state is
completed , returnCreateIterResultObject (undefined ,true ). Assert : state is eithersuspended-start orsuspended-yield .- Let genContext be generator.[[GeneratorContext]].
- Let methodContext be the
running execution context . - Suspend methodContext.
- Set generator.[[GeneratorState]] to
executing . - Push genContext onto the
execution context stack ; genContext is now therunning execution context . Resume the suspended evaluation of genContext usingNormalCompletion (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 ? result.
27.5.3.4 GeneratorResumeAbrupt ( generator, abruptCompletion, generatorBrand )
The abstract operation GeneratorResumeAbrupt takes arguments generator (an
- Let state be ?
GeneratorValidate (generator, generatorBrand). - If state is
suspended-start , then- Set generator.[[GeneratorState]] to
completed . - NOTE: 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 to
completed .
- Set generator.[[GeneratorState]] to
- If state is
completed , then- If abruptCompletion is a
return completion , then- Return
CreateIterResultObject (abruptCompletion.[[Value]],true ).
- Return
- Return ? abruptCompletion.
- If abruptCompletion is a
Assert : state issuspended-yield .- Let genContext be generator.[[GeneratorContext]].
- Let methodContext be the
running execution context . - Suspend methodContext.
- Set generator.[[GeneratorState]] to
executing . - 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 theCompletion 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 ? result.
27.5.3.5 GetGeneratorKind ( )
The abstract operation GetGeneratorKind takes no arguments and returns
- 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 (an Object that conforms to the IteratorResult interface) and returns either a
- 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]] to
suspended-yield . - Remove genContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - Let callerContext be the
running execution context . - Resume callerContext passing
NormalCompletion (iterNextObj). If genContext is ever resumed again, let resumptionValue be theCompletion Record with which it is resumed. Assert : If control reaches here, then genContext is therunning execution context again.- Return resumptionValue.
27.5.3.7 Yield ( value )
The abstract operation Yield takes argument value (an
- Let generatorKind be
GetGeneratorKind (). - If generatorKind is
async , return ?AsyncGeneratorYield (?Await (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 operation 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]] to
undefined . - Let callerContext be the
running execution context . - Let calleeContext be a new
execution context . - Set the Function of calleeContext to
null . - Set the
Realm of calleeContext tothe current Realm Record . - Set the ScriptOrModule of calleeContext to callerContext's ScriptOrModule.
- If callerContext is not already suspended, suspend callerContext.
- Push calleeContext onto the
execution context stack ; calleeContext is now therunning execution context . - Perform
GeneratorStart (generator, closure). - Remove calleeContext from the
execution context stack and restore callerContext as therunning execution context . - Return generator.
27.6 AsyncGenerator Objects
An AsyncGenerator 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 promiseCapability be !
NewPromiseCapability (%Promise% ). - Let result be
Completion (AsyncGeneratorValidate (generator,empty )). IfAbruptRejectPromise (result, promiseCapability).- Let state be generator.[[AsyncGeneratorState]].
- If state is
completed , then- Let iteratorResult be
CreateIterResultObject (undefined ,true ). - Perform !
Call (promiseCapability.[[Resolve]],undefined , « iteratorResult »). - Return promiseCapability.[[Promise]].
- Let iteratorResult be
- Let completion be
NormalCompletion (value). - Perform
AsyncGeneratorEnqueue (generator, completion, promiseCapability). - If state is either
suspended-start orsuspended-yield , then- Perform
AsyncGeneratorResume (generator, completion).
- Perform
- Else,
Assert : state is eitherexecuting orawaiting-return .
- Return promiseCapability.[[Promise]].
27.6.1.3 AsyncGenerator.prototype.return ( value )
- Let generator be the
this value. - Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let result be
Completion (AsyncGeneratorValidate (generator,empty )). IfAbruptRejectPromise (result, promiseCapability).- Let completion be
Completion Record { [[Type]]:return , [[Value]]: value, [[Target]]:empty }. - Perform
AsyncGeneratorEnqueue (generator, completion, promiseCapability). - Let state be generator.[[AsyncGeneratorState]].
- If state is either
suspended-start orcompleted , then- Set generator.[[AsyncGeneratorState]] to
awaiting-return . - Perform !
AsyncGeneratorAwaitReturn (generator).
- Set generator.[[AsyncGeneratorState]] to
- Else if state is
suspended-yield , then- Perform
AsyncGeneratorResume (generator, completion).
- Perform
- Else,
Assert : state is eitherexecuting orawaiting-return .
- Return promiseCapability.[[Promise]].
27.6.1.4 AsyncGenerator.prototype.throw ( exception )
- Let generator be the
this value. - Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let result be
Completion (AsyncGeneratorValidate (generator,empty )). IfAbruptRejectPromise (result, promiseCapability).- Let state be generator.[[AsyncGeneratorState]].
- If state is
suspended-start , then- Set generator.[[AsyncGeneratorState]] to
completed . - Set state to
completed .
- Set generator.[[AsyncGeneratorState]] to
- If state is
completed , then- Perform !
Call (promiseCapability.[[Reject]],undefined , « exception »). - Return promiseCapability.[[Promise]].
- Perform !
- Let completion be
ThrowCompletion (exception). - Perform
AsyncGeneratorEnqueue (generator, completion, promiseCapability). - If state is
suspended-yield , then- Perform
AsyncGeneratorResume (generator, completion).
- Perform
- Else,
Assert : state is eitherexecuting orawaiting-return .
- Return promiseCapability.[[Promise]].
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 | Type | Description |
|---|---|---|
| [[AsyncGeneratorState]] | The current execution state of the async generator. | |
| [[AsyncGeneratorContext]] | an |
The |
| [[AsyncGeneratorQueue]] | a |
|
| [[GeneratorBrand]] | a String or |
A brand used to distinguish different kinds of async generators. The [[GeneratorBrand]] of async generators declared by |
27.6.3 AsyncGenerator Abstract Operations
27.6.3.1 AsyncGeneratorRequest Records
An AsyncGeneratorRequest is a
They have the following fields:
| Field Name | Value | Meaning |
|---|---|---|
| [[Completion]] | a |
The |
| [[Capability]] | a |
The promise capabilities associated with this request. |
27.6.3.2 AsyncGeneratorStart ( generator, generatorBody )
The abstract operation AsyncGeneratorStart takes arguments generator (an AsyncGenerator) and generatorBody (a
Assert : generator.[[AsyncGeneratorState]] isundefined .- Let genContext be the
running execution context . - Set the Generator component of genContext to generator.
- Let closure be a new
Abstract Closure with no parameters that captures generatorBody and performs the following steps when called:- Let acGenContext be the
running execution context . - Let acGenerator be the Generator component of acGenContext.
- If generatorBody is a
Parse Node , then- Let result be
Completion (Evaluation of generatorBody).
- Let result be
- Else,
Assert : generatorBody is anAbstract Closure with no parameters.- Let result be
Completion (generatorBody()).
Assert : If we return here, the async generator either threw an exception or performed either an implicit or explicit return.- Remove acGenContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - Set acGenerator.[[AsyncGeneratorState]] to
completed . - If result is a
normal completion , set result toNormalCompletion (undefined ). - If result is a
return completion , set result toNormalCompletion (result.[[Value]]). - Perform
AsyncGeneratorCompleteStep (acGenerator, result,true ). - Perform
AsyncGeneratorDrainQueue (acGenerator). - Return
undefined .
- Let acGenContext be the
- Set the code evaluation state of genContext such that when evaluation is resumed for that
execution context , closure will be called with no arguments. - Set generator.[[AsyncGeneratorContext]] to genContext.
- Set generator.[[AsyncGeneratorState]] to
suspended-start . - Set generator.[[AsyncGeneratorQueue]] to a new empty
List . - Return
unused .
27.6.3.3 AsyncGeneratorValidate ( generator, generatorBrand )
The abstract operation AsyncGeneratorValidate takes arguments generator (an
- Perform ?
RequireInternalSlot (generator, [[AsyncGeneratorContext]]). - Perform ?
RequireInternalSlot (generator, [[AsyncGeneratorState]]). - Perform ?
RequireInternalSlot (generator, [[AsyncGeneratorQueue]]). - If generator.[[GeneratorBrand]] is not generatorBrand, throw a
TypeError exception. - Return
unused .
27.6.3.4 AsyncGeneratorEnqueue ( generator, completion, promiseCapability )
The abstract operation AsyncGeneratorEnqueue takes arguments generator (an AsyncGenerator), completion (a
- Let request be
AsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }. - Append request to generator.[[AsyncGeneratorQueue]].
- Return
unused .
27.6.3.5 AsyncGeneratorCompleteStep ( generator, completion, done [ , realm ] )
The abstract operation AsyncGeneratorCompleteStep takes arguments generator (an AsyncGenerator), completion (a
Assert : generator.[[AsyncGeneratorQueue]] is not empty.- Let next be the first element of generator.[[AsyncGeneratorQueue]].
- Remove the first element from generator.[[AsyncGeneratorQueue]].
- Let promiseCapability be next.[[Capability]].
- Let value be completion.[[Value]].
- If completion is a
throw completion , then- Perform !
Call (promiseCapability.[[Reject]],undefined , « value »).
- Perform !
- Else,
Assert : completion is anormal completion .- If realm is present, then
- Let oldRealm be the
running execution context 'sRealm . - Set the
running execution context 'sRealm to realm. - Let iteratorResult be
CreateIterResultObject (value, done). - Set the
running execution context 'sRealm to oldRealm.
- Let oldRealm be the
- Else,
- Let iteratorResult be
CreateIterResultObject (value, done).
- Let iteratorResult be
- Perform !
Call (promiseCapability.[[Resolve]],undefined , « iteratorResult »).
- Return
unused .
27.6.3.6 AsyncGeneratorResume ( generator, completion )
The abstract operation AsyncGeneratorResume takes arguments generator (an AsyncGenerator) and completion (a
Assert : generator.[[AsyncGeneratorState]] is eithersuspended-start orsuspended-yield .- Let genContext be generator.[[AsyncGeneratorContext]].
- Let callerContext be the
running execution context . - Suspend callerContext.
- Set generator.[[AsyncGeneratorState]] to
executing . - 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 theCompletion 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
unused .
27.6.3.7 AsyncGeneratorUnwrapYieldResumption ( resumptionValue )
The abstract operation AsyncGeneratorUnwrapYieldResumption takes argument resumptionValue (a
- If resumptionValue is not a
return completion , return ? resumptionValue. - Let awaited be
Completion (Await (resumptionValue.[[Value]])). - If awaited is a
throw completion , return ? awaited. Assert : awaited is anormal completion .- Return
Completion Record { [[Type]]:return , [[Value]]: awaited.[[Value]], [[Target]]:empty }.
27.6.3.8 AsyncGeneratorYield ( value )
The abstract operation AsyncGeneratorYield takes argument value (an
- 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 .- Let completion be
NormalCompletion (value). Assert : Theexecution context stack has at least two elements.- Let previousContext be the second to top element of the
execution context stack . - Let previousRealm be previousContext's
Realm . - Perform
AsyncGeneratorCompleteStep (generator, completion,false , previousRealm). - Let queue be generator.[[AsyncGeneratorQueue]].
- If queue is not empty, then
- NOTE: Execution continues without suspending the generator.
- Let toYield be the first element of queue.
- Let resumptionValue be
Completion (toYield.[[Completion]]). - Return ?
AsyncGeneratorUnwrapYieldResumption (resumptionValue).
- Else,
- Set generator.[[AsyncGeneratorState]] to
suspended-yield . - Remove genContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - Let callerContext be the
running execution context . - Resume callerContext passing
undefined . If genContext is ever resumed again, let resumptionValue be theCompletion Record with which it is resumed. Assert : If control reaches here, then genContext is therunning execution context again.- Return ?
AsyncGeneratorUnwrapYieldResumption (resumptionValue).
- Set generator.[[AsyncGeneratorState]] to
27.6.3.9 AsyncGeneratorAwaitReturn ( generator )
The abstract operation AsyncGeneratorAwaitReturn takes argument generator (an AsyncGenerator) and returns either a
- Let queue be generator.[[AsyncGeneratorQueue]].
Assert : queue is not empty.- Let next be the first element of queue.
- Let completion be
Completion (next.[[Completion]]). Assert : completion is areturn completion .- Let promise be ?
PromiseResolve (%Promise% , completion.[[Value]]). - Let fulfilledClosure be a new
Abstract Closure with parameters (value) that captures generator and performs the following steps when called:- Set generator.[[AsyncGeneratorState]] to
completed . - Let result be
NormalCompletion (value). - Perform
AsyncGeneratorCompleteStep (generator, result,true ). - Perform
AsyncGeneratorDrainQueue (generator). - Return
undefined .
- Set generator.[[AsyncGeneratorState]] to
- Let onFulfilled be
CreateBuiltinFunction (fulfilledClosure, 1,"" , « »). - Let rejectedClosure be a new
Abstract Closure with parameters (reason) that captures generator and performs the following steps when called:- Set generator.[[AsyncGeneratorState]] to
completed . - Let result be
ThrowCompletion (reason). - Perform
AsyncGeneratorCompleteStep (generator, result,true ). - Perform
AsyncGeneratorDrainQueue (generator). - Return
undefined .
- Set generator.[[AsyncGeneratorState]] to
- Let onRejected be
CreateBuiltinFunction (rejectedClosure, 1,"" , « »). - Perform
PerformPromiseThen (promise, onFulfilled, onRejected). - Return
unused .
27.6.3.10 AsyncGeneratorDrainQueue ( generator )
The abstract operation AsyncGeneratorDrainQueue takes argument generator (an AsyncGenerator) and returns
Assert : generator.[[AsyncGeneratorState]] iscompleted .- Let queue be generator.[[AsyncGeneratorQueue]].
- If queue is empty, return
unused . - Let done be
false . - Repeat, while done is
false ,- Let next be the first element of queue.
- Let completion be
Completion (next.[[Completion]]). - If completion is a
return completion , then- Set generator.[[AsyncGeneratorState]] to
awaiting-return . - Perform !
AsyncGeneratorAwaitReturn (generator). - Set done to
true .
- Set generator.[[AsyncGeneratorState]] to
- Else,
- If completion is a
normal completion , then- Set completion to
NormalCompletion (undefined ).
- Set completion to
- Perform
AsyncGeneratorCompleteStep (generator, completion,true ). - If queue is empty, set done to
true .
- If completion is a
- Return
unused .
27.6.3.11 CreateAsyncIteratorFromClosure ( closure, generatorBrand, generatorPrototype )
The abstract operation CreateAsyncIteratorFromClosure takes arguments closure (an
- NOTE: closure can contain uses of the
Await operation and uses of theYield operation 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]] to
undefined . - Let callerContext be the
running execution context . - Let calleeContext be a new
execution context . - Set the Function of calleeContext to
null . - Set the
Realm of calleeContext tothe current Realm Record . - Set the ScriptOrModule of calleeContext to callerContext's ScriptOrModule.
- If callerContext is not already suspended, suspend callerContext.
- Push calleeContext onto the
execution context stack ; calleeContext is now therunning execution context . - Perform
AsyncGeneratorStart (generator, closure). - Remove calleeContext from the
execution context stack and restore callerContext as therunning execution context . - Return generator.
27.7 AsyncFunction Objects
AsyncFunctions 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 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. - may be used as the value of an
extendsclause of a class definition. Subclassconstructors 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 asyncfunction objects create direct instances of AsyncFunction. There is no syntactic means to create instances of AsyncFunction subclasses.
27.7.1.1 AsyncFunction ( ...parameterArgs, bodyArg )
The last argument (if any) specifies the body (executable code) of an async function. Any preceding arguments specify formal parameters.
This function performs the following steps when called:
- Let C be the
active function object . - If bodyArg is not present, set bodyArg to the empty String.
- Return ?
CreateDynamicFunction (C, NewTarget,async , parameterArgs, bodyArg).
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
"length" property whose value is1 𝔽. - has a
"name" property whose value is"AsyncFunction" . - has the following properties:
27.7.2.1 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 30 . - 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
AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context. - Perform
AsyncBlockStart (promiseCapability, asyncFunctionBody, asyncContext). - Return
unused .
27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext )
The abstract operation AsyncBlockStart takes arguments promiseCapability (a
Assert : promiseCapability is aPromiseCapability Record .- Let runningContext be the
running execution context . - Let closure be a new
Abstract Closure with no parameters that captures promiseCapability and asyncBody and performs the following steps when called:- Let acAsyncContext be the
running execution context . - Let result be
Completion (Evaluation of asyncBody). Assert : If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.- Remove acAsyncContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - If result is a
normal completion , then- Perform !
Call (promiseCapability.[[Resolve]],undefined , «undefined »).
- Perform !
- Else if result is a
return completion , then- Perform !
Call (promiseCapability.[[Resolve]],undefined , « result.[[Value]] »).
- Perform !
- Else,
Assert : result is athrow completion .- Perform !
Call (promiseCapability.[[Reject]],undefined , « result.[[Value]] »).
- Return
unused .
- Let acAsyncContext be the
- Set the code evaluation state of asyncContext such that when evaluation is resumed for that
execution context , closure will be called with no arguments. - 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 anormal completion with a value ofunused . The possible sources of this value areAwait or, if the async function doesn't await anything, step3.h above.- Return
unused .
27.7.5.3 Await ( value )
The abstract operation Await takes argument value (an
- Let asyncContext be the
running execution context . - Let promise be ?
PromiseResolve (%Promise% , value). - Let fulfilledClosure be a new
Abstract Closure with parameters (v) that captures asyncContext and performs the following steps when called:- Let prevContext be the
running execution context . - Suspend prevContext.
- Push asyncContext onto the
execution context stack ; asyncContext is now therunning execution context . Resume the suspended evaluation of asyncContext usingNormalCompletion (v) as the result of the operation that suspended it.Assert : When we reach this step, asyncContext has already been removed from theexecution context stack and prevContext is the currentlyrunning execution context .- Return
undefined .
- Let prevContext be the
- Let onFulfilled be
CreateBuiltinFunction (fulfilledClosure, 1,"" , « »). - Let rejectedClosure be a new
Abstract Closure with parameters (reason) that captures asyncContext and performs the following steps when called:- Let prevContext be the
running execution context . - Suspend prevContext.
- Push asyncContext onto the
execution context stack ; asyncContext is now therunning execution context . Resume the suspended evaluation of asyncContext usingThrowCompletion (reason) as the result of the operation that suspended it.Assert : When we reach this step, asyncContext has already been removed from theexecution context stack and prevContext is the currentlyrunning execution context .- Return
undefined .
- Let prevContext be the
- Let onRejected be
CreateBuiltinFunction (rejectedClosure, 1,"" , « »). - Perform
PerformPromiseThen (promise, onFulfilled, onRejected). - Remove asyncContext from the
execution context stack and restore theexecution context that is at the top of theexecution context stack as therunning execution context . - Let callerContext be the
running execution context . - Resume callerContext passing
empty . If asyncContext is ever resumed again, let completion be theCompletion Record with which it is resumed. Assert : If control reaches here, then asyncContext is therunning execution context again.- Return completion.