25 Control Abstraction Objects
25.1 Iteration
25.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.
25.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. |
25.1.1.2 The Iterator Interface
An object that implements the Iterator interface must include the property in
| Property | Value | Requirements |
|---|---|---|
next
|
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 done property is next method of that object should also return an IteratorResult object whose done property is |
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 |
|---|---|---|
return
|
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 done property whose value is value property with the value passed as the argument of the return method. However, this requirement is not enforced.
|
throw
|
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 done property whose value is |
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.
25.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. |
25.1.1.4 The AsyncIterator Interface
An object that implements the AsyncIterator interface must include the properties in
| Property | Value | Requirements |
|---|---|---|
next |
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 |
|---|---|---|
return |
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 |
throw |
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.
25.1.1.5 The IteratorResult Interface
The IteratorResult interface includes the properties listed in
| Property | Value | Requirements |
|---|---|---|
done
|
Either |
This is the result status of an iterator next method call. If the end of the iterator was reached done is done is done property (either own or inherited) does not exist, it is consider to have the value |
value
|
Any |
If done is value is value property may be absent from the conforming object if it does not inherit an explicit value property.
|
25.1.2 The %IteratorPrototype% Object
The
- has a [[Prototype]] internal slot whose value is the intrinsic object
%ObjectPrototype% . - 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]()))
25.1.2.1 %IteratorPrototype% [ @@iterator ] ( )
The following steps are taken:
- Return the
this value.
The value of the name property of this function is "[Symbol.iterator]".
25.1.3 The %AsyncIteratorPrototype% Object
The
- has a [[Prototype]] internal slot whose value is the intrinsic object
%ObjectPrototype% . - is an ordinary object.
All objects defined in this specification that implement the AsyncIterator interface also inherit from
25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
The following steps are taken:
- Return the
this value.
The value of the name property of this function is "[Symbol.asyncIterator]".
25.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
25.1.4.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )
The abstract operation CreateAsyncFromSyncIterator is used to create an async iterator
- Let asyncIterator be !
ObjectCreate (%AsyncFromSyncIteratorPrototype% , « [[SyncIteratorRecord]] »). Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord.- Return ?
GetIterator (asyncIterator,async ).
25.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 the intrinsic object
%AsyncIteratorPrototype% . - has the following properties:
25.1.4.2.1 %AsyncFromSyncIteratorPrototype% .next ( value )
- Let O be the
this value. - Let promiseCapability be !
NewPromiseCapability (%Promise% ). - If
Type (O) is not Object, or if O does not have a [[SyncIteratorRecord]] internal slot, then- Let invalidIteratorError be a newly created
TypeError object. - Perform !
Call (promiseCapability.[[Reject]],undefined , « invalidIteratorError »). - Return promiseCapability.[[Promise]].
- Let invalidIteratorError be a newly created
- Let syncIteratorRecord be O.[[SyncIteratorRecord]].
- Let nextResult be
IteratorNext (syncIteratorRecord, value). IfAbruptRejectPromise (nextResult, promiseCapability).- Let nextDone be
IteratorComplete (nextResult). IfAbruptRejectPromise (nextDone, promiseCapability).- Let nextValue be
IteratorValue (nextResult). IfAbruptRejectPromise (nextValue, promiseCapability).- Let valueWrapperCapability be !
NewPromiseCapability (%Promise% ). - Perform !
Call (valueWrapperCapability.[[Resolve]],undefined , « nextValue »). - Let steps be the algorithm steps defined in
Async-from-Sync Iterator Value Unwrap Functions . - Let onFulfilled be
CreateBuiltinFunction (steps, « [[Done]] »). Set onFulfilled.[[Done]] to nextDone.- Perform !
PerformPromiseThen (valueWrapperCapability.[[Promise]], onFulfilled,undefined , promiseCapability). - Return promiseCapability.[[Promise]].
25.1.4.2.2 %AsyncFromSyncIteratorPrototype% .return ( value )
- Let O be the
this value. - Let promiseCapability be !
NewPromiseCapability (%Promise% ). - If
Type (O) is not Object, or if O does not have a [[SyncIteratorRecord]] internal slot, then- Let invalidIteratorError be a newly created
TypeError object. - Perform !
Call (promiseCapability.[[Reject]],undefined , « invalidIteratorError »). - Return promiseCapability.[[Promise]].
- Let invalidIteratorError be a newly created
- 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 !
- Let returnResult be
Call (return, syncIterator, « value »). IfAbruptRejectPromise (returnResult, promiseCapability).- If
Type (returnResult) is not Object, then- Perform !
Call (promiseCapability.[[Reject]],undefined , « a newly createdTypeError object »). - Return promiseCapability.[[Promise]].
- Perform !
- Let returnDone be
IteratorComplete (returnResult). IfAbruptRejectPromise (returnDone, promiseCapability).- Let returnValue be
IteratorValue (returnResult). IfAbruptRejectPromise (returnValue, promiseCapability).- Let valueWrapperCapability be !
NewPromiseCapability (%Promise% ). - Perform !
Call (valueWrapperCapability.[[Resolve]],undefined , « returnValue »). - Let steps be the algorithm steps defined in
Async-from-Sync Iterator Value Unwrap Functions . - Let onFulfilled be
CreateBuiltinFunction (steps, « [[Done]] »). Set onFulfilled.[[Done]] to returnDone.- Perform !
PerformPromiseThen (valueWrapperCapability.[[Promise]], onFulfilled,undefined , promiseCapability). - Return promiseCapability.[[Promise]].
25.1.4.2.3 %AsyncFromSyncIteratorPrototype% .throw ( value )
- Let O be the
this value. - Let promiseCapability be !
NewPromiseCapability (%Promise% ). - If
Type (O) is not Object, or if O does not have a [[SyncIteratorRecord]] internal slot, then- Let invalidIteratorError be a newly created
TypeError object. - Perform !
Call (promiseCapability.[[Reject]],undefined , « invalidIteratorError »). - Return promiseCapability.[[Promise]].
- Let invalidIteratorError be a newly created
- 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 !
- Let throwResult be
Call (throw, syncIterator, « value »). IfAbruptRejectPromise (throwResult, promiseCapability).- If
Type (throwResult) is not Object, then- Perform !
Call (promiseCapability.[[Reject]],undefined , « a newly createdTypeError object »). - Return promiseCapability.[[Promise]].
- Perform !
- Let throwDone be
IteratorComplete (throwResult). IfAbruptRejectPromise (throwDone, promiseCapability).- Let throwValue be
IteratorValue (throwResult). IfAbruptRejectPromise (throwValue, promiseCapability).- Let valueWrapperCapability be !
NewPromiseCapability (%Promise% ). - Perform !
Call (valueWrapperCapability.[[Resolve]],undefined , « throwValue »). - Let steps be the algorithm steps defined in
Async-from-Sync Iterator Value Unwrap Functions . - Let onFulfilled be
CreateBuiltinFunction (steps, « [[Done]] »). Set onFulfilled.[[Done]] to throwDone.- Perform !
PerformPromiseThen (valueWrapperCapability.[[Promise]], onFulfilled,undefined , promiseCapability). - Return promiseCapability.[[Promise]].
25.1.4.2.4 %AsyncFromSyncIteratorPrototype% [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "Async-from-Sync Iterator".
This property has the attributes { [[Writable]]:
25.1.4.2.5 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 methods of value field 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. Each async iterator value unwrap function has a [[Done]] internal slot.
When an async-from-sync iterator value unwrap function F is called with argument value, the following steps are taken:
- Return !
CreateIterResultObject (value, F.[[Done]]).
25.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 |
25.2 GeneratorFunction Objects
GeneratorFunction objects are functions that are usually created by evaluating
25.2.1 The GeneratorFunction Constructor
The GeneratorFunction
- is the intrinsic object
%GeneratorFunction% . - 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 specifiedGeneratorFunctionbehaviour must include asupercall to theGeneratorFunctionconstructor 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 ofGeneratorFunction. There is no syntactic means to create instances ofGeneratorFunctionsubclasses.
25.2.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
25.2.2 Properties of the GeneratorFunction Constructor
The GeneratorFunction
- is a standard built-in
function object that inherits from theFunctionconstructor . - has a [[Prototype]] internal slot whose value is the intrinsic object
%Function% . - has a
nameproperty whose value is"GeneratorFunction". - has the following properties:
25.2.2.1 GeneratorFunction.length
This is a
25.2.2.2 GeneratorFunction.prototype
The initial value of GeneratorFunction.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
25.2.3 Properties of the GeneratorFunction Prototype Object
The GeneratorFunction prototype object:
- 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 27 orTable 68 . - is the value of the
prototypeproperty of the intrinsic object%GeneratorFunction% . - is the intrinsic object
%Generator% (see Figure 2). - has a [[Prototype]] internal slot whose value is the intrinsic object
%FunctionPrototype% .
25.2.3.1 GeneratorFunction.prototype.constructor
The initial value of GeneratorFunction.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.2.3.2 GeneratorFunction.prototype.prototype
The value of GeneratorFunction.prototype.prototype is the
This property has the attributes { [[Writable]]:
25.2.3.3 GeneratorFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "GeneratorFunction".
This property has the attributes { [[Writable]]:
25.2.4 GeneratorFunction Instances
Every GeneratorFunction instance is an ECMAScript "generator".
Each GeneratorFunction instance has the following own properties:
25.2.4.1 length
The specification for the length property of Function instances given in
25.2.4.2 name
The specification for the name property of Function instances given in
25.2.4.3 prototype
Whenever a GeneratorFunction instance is created another ordinary object is also created and is the initial value of the generator function's prototype property. The value of the prototype property is used to initialize the [[Prototype]] internal slot of a newly created Generator object when the generator
This property has the attributes { [[Writable]]:
Unlike Function instances, the object that is the value of the a GeneratorFunction's prototype property does not have a constructor property whose value is the GeneratorFunction instance.
25.3 AsyncGeneratorFunction Objects
AsyncGeneratorFunction objects are functions that are usually created by evaluating
25.3.1 The AsyncGeneratorFunction Constructor
The AsyncGeneratorFunction
- is the intrinsic object
%AsyncGeneratorFunction% . - 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 specifiedAsyncGeneratorFunctionbehaviour must include asupercall to theAsyncGeneratorFunctionconstructor 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 ofAsyncGeneratorFunction. There is no syntactic means to create instances ofAsyncGeneratorFunctionsubclasses.
25.3.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,"async generator", args).
See NOTE for
25.3.2 Properties of the AsyncGeneratorFunction Constructor
The AsyncGeneratorFunction
- is a standard built-in
function object that inherits from theFunctionconstructor . - has a [[Prototype]] internal slot whose value is the intrinsic object
%Function% . - has a
nameproperty whose value is"AsyncGeneratorFunction". - has the following properties:
25.3.2.1 AsyncGeneratorFunction.length
This is a
25.3.2.2 AsyncGeneratorFunction.prototype
The initial value of AsyncGeneratorFunction.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
25.3.3 Properties of the AsyncGeneratorFunction Prototype Object
The AsyncGeneratorFunction prototype object:
- 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 27 orTable 69 . - is the value of the
prototypeproperty of the intrinsic object%AsyncGeneratorFunction% . - is the intrinsic object
%AsyncGenerator% . - has a [[Prototype]] internal slot whose value is the intrinsic object
%FunctionPrototype% .
25.3.3.1 AsyncGeneratorFunction.prototype.constructor
The initial value of AsyncGeneratorFunction.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.3.3.2 AsyncGeneratorFunction.prototype.prototype
The value of AsyncGeneratorFunction.prototype.prototype is the
This property has the attributes { [[Writable]]:
25.3.3.3 AsyncGeneratorFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "AsyncGeneratorFunction".
This property has the attributes { [[Writable]]:
25.3.4 AsyncGeneratorFunction Instances
Every AsyncGeneratorFunction instance is an ECMAScript "generator".
Each AsyncGeneratorFunction instance has the following own properties:
25.3.4.1 length
The value of the length property is an integer that indicates the typical number of arguments expected by the AsyncGeneratorFunction. However, the language permits the function to be invoked with some other number of arguments. The behaviour of an AsyncGeneratorFunction when invoked on a number of arguments other than the number specified by its length property depends on the function.
This property has the attributes { [[Writable]]:
25.3.4.2 name
The specification for the name property of Function instances given in
25.3.4.3 prototype
Whenever an AsyncGeneratorFunction instance is created another ordinary object is also created and is the initial value of the async generator function's prototype property. The value of the prototype property is used to initialize the [[Prototype]] internal slot of a newly created AsyncGenerator object when the generator
This property has the attributes { [[Writable]]:
Unlike function instances, the object that is the value of the an AsyncGeneratorFunction's prototype property does not have a constructor property whose value is the AsyncGeneratorFunction instance.
25.4 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 value of the prototype property of the Generator function that created the instance. Generator instances indirectly inherit properties from the Generator Prototype intrinsic,
25.4.1 Properties of the Generator Prototype Object
The Generator prototype object:
- is the intrinsic object
%GeneratorPrototype% . - is the initial value of the
prototypeproperty of the intrinsic object%Generator% (the GeneratorFunction.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 the intrinsic object
%IteratorPrototype% . - has properties that are indirectly inherited by all Generator instances.
25.4.1.1 Generator.prototype.constructor
The initial value of Generator.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.4.1.2 Generator.prototype.next ( value )
The next method performs the following steps:
- Let g be the
this value. - Return ?
GeneratorResume (g, value).
25.4.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).
25.4.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).
25.4.1.5 Generator.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "Generator".
This property has the attributes { [[Writable]]:
25.4.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: "suspendedStart", "suspendedYield", "executing", and "completed".
|
| [[GeneratorContext]] |
The |
25.4.3 Generator Abstract Operations
25.4.3.1 GeneratorStart ( generator, generatorBody )
The abstract operation GeneratorStart with arguments generator and generatorBody performs the following steps:
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:- Let result be the result of evaluating 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]] to"completed".- 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 ).
Set generator.[[GeneratorContext]] to genContext.Set generator.[[GeneratorState]] to"suspendedStart".- Return
NormalCompletion (undefined ).
25.4.3.2 GeneratorValidate ( generator )
The abstract operation GeneratorValidate with argument generator performs the following steps:
- If
Type (generator) is not Object, throw aTypeError exception. - If generator does not have a [[GeneratorState]] internal slot, 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.
25.4.3.3 GeneratorResume ( generator, value )
The abstract operation GeneratorResume with arguments generator and value performs the following steps:
- Let state be ?
GeneratorValidate (generator). - If state is
"completed", returnCreateIterResultObject (undefined ,true ). Assert : state is either"suspendedStart"or"suspendedYield".- 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
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).
25.4.3.4 GeneratorResumeAbrupt ( generator, abruptCompletion )
The abstract operation GeneratorResumeAbrupt with arguments generator and abruptCompletion performs the following steps:
- Let state be ?
GeneratorValidate (generator). - If state is
"suspendedStart", thenSet generator.[[GeneratorState]] to"completed".- 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".
- 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 is"suspendedYield".- 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 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).
25.4.3.5 GetGeneratorKind ( )
- 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 .
25.4.3.6 GeneratorYield ( iterNextObj )
The abstract operation GeneratorYield with argument iterNextObj performs the following steps:
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]] to"suspendedYield".- 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.
25.5 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 value of the prototype property of the AsyncGenerator function that created the instance. AsyncGenerator instances indirectly inherit properties from the AsyncGenerator Prototype intrinsic,
25.5.1 Properties of the AsyncGenerator Prototype Object
The AsyncGenerator prototype object:
- is the intrinsic object
%AsyncGeneratorPrototype% . - is the initial value of the
prototypeproperty of the intrinsic object%AsyncGenerator% (the AsyncGeneratorFunction.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 the intrinsic object
%AsyncIteratorPrototype% . - has properties that are indirectly inherited by all AsyncGenerator instances.
25.5.1.1 AsyncGenerator.prototype.constructor
The initial value of AsyncGenerator.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.5.1.2 AsyncGenerator.prototype.next ( value )
- Let generator be the
this value. - Let completion be
NormalCompletion (value). - Return !
AsyncGeneratorEnqueue (generator, completion).
25.5.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).
25.5.1.4 AsyncGenerator.prototype.throw ( exception )
- Let generator be the
this value. - Let completion be
ThrowCompletion (exception). - Return !
AsyncGeneratorEnqueue (generator, completion).
25.5.1.5 AsyncGenerator.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "AsyncGenerator".
This property has the attributes { [[Writable]]:
25.5.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: "suspendedStart", "suspendedYield", "executing", "awaiting-return", and "completed". |
| [[AsyncGeneratorContext]] | The |
| [[AsyncGeneratorQueue]] | A |
25.5.3 AsyncGenerator Abstract Operations
25.5.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 PromiseCapability record | The promise capabilities associated with this request. |
25.5.3.2 AsyncGeneratorStart ( generator, generatorBody )
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:- Let result be the result of evaluating 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]] to"completed".- 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 ).
Set generator.[[AsyncGeneratorContext]] to genContext.Set generator.[[AsyncGeneratorState]] to"suspendedStart".Set generator.[[AsyncGeneratorQueue]] to a new emptyList .- Return
undefined .
25.5.3.3 AsyncGeneratorResolve ( generator, value, done )
Assert : generator is an AsyncGenerator instance.- Let queue be generator.[[AsyncGeneratorQueue]].
Assert : queue is not an emptyList .- Remove the first element from queue and let next be the value of that element.
- Let promiseCapability be next.[[Capability]].
- Let iteratorResult be !
CreateIterResultObject (value, done). - Perform !
Call (promiseCapability.[[Resolve]],undefined , « iteratorResult »). - Perform !
AsyncGeneratorResumeNext (generator). - Return
undefined .
25.5.3.4 AsyncGeneratorReject ( generator, exception )
Assert : generator is an AsyncGenerator instance.- Let queue be generator.[[AsyncGeneratorQueue]].
Assert : queue is not an emptyList .- Remove the first element from queue and let next be the value of that element.
- Let promiseCapability be next.[[Capability]].
- Perform !
Call (promiseCapability.[[Reject]],undefined , « exception »). - Perform !
AsyncGeneratorResumeNext (generator). - Return
undefined .
25.5.3.5 AsyncGeneratorResumeNext ( generator )
Assert : generator is an AsyncGenerator instance.- Let state be generator.[[AsyncGeneratorState]].
Assert : state is not"executing".- 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]] to"awaiting-return".- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Perform !
Call (promiseCapability.[[Resolve]],undefined , « completion.[[Value]] »). - Let stepsFulfilled be the algorithm steps defined in
AsyncGeneratorResumeNext Return Processor Fulfilled Functions . - Let onFulfilled be
CreateBuiltinFunction (stepsFulfilled, « [[Generator]] »). Set onFulfilled.[[Generator]] to generator.- Let stepsRejected be the algorithm steps defined in
AsyncGeneratorResumeNext Return Processor Rejected Functions . - Let onRejected be
CreateBuiltinFunction (stepsRejected, « [[Generator]] »). Set onRejected.[[Generator]] to generator.- Let throwawayCapability be !
NewPromiseCapability (%Promise% ). Set throwawayCapability.[[Promise]].[[PromiseIsHandled]] totrue .- Perform !
PerformPromiseThen (promiseCapability.[[Promise]], onFulfilled, onRejected, throwawayCapability). - 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 either"suspendedStart"or"suspendedYield".- 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 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 .
25.5.3.5.1 AsyncGeneratorResumeNext Return Processor Fulfilled Functions
An
When an
Set F.[[Generator]].[[AsyncGeneratorState]] to"completed".- Return !
AsyncGeneratorResolve (F.[[Generator]], value,true ).
The length property of an
25.5.3.5.2 AsyncGeneratorResumeNext Return Processor Rejected Functions
An
When an
Set F.[[Generator]].[[AsyncGeneratorState]] to"completed".- Return !
AsyncGeneratorReject (F.[[Generator]], reason).
The length property of an
25.5.3.6 AsyncGeneratorEnqueue ( generator, completion )
Assert : completion is aCompletion Record .- Let promiseCapability be !
NewPromiseCapability (%Promise% ). - If
Type (generator) is not Object, or if generator does not have an [[AsyncGeneratorState]] internal slot, 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]].
25.5.3.7 AsyncGeneratorYield ( value )
The abstract operation AsyncGeneratorYield with argument value performs the following steps:
- 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]] to"suspendedYield".- 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.
25.6 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 a Job to call the functionf. -
A promise
pis rejected ifp.then(f, r)will immediately enqueue a Job 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.
25.6.1 Promise Abstract Operations
25.6.1.1 PromiseCapability Records
A PromiseCapability 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. |
25.6.1.1.1 IfAbruptRejectPromise ( value, capability )
IfAbruptRejectPromise is a shorthand for a sequence of algorithm steps that use a PromiseCapability
- 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 , let value be value.[[Value]].
25.6.1.2 PromiseReaction Records
The PromiseReaction is a
PromiseReaction records have the fields listed in
| Field Name | Value | Meaning |
|---|---|---|
| [[Capability]] |
A PromiseCapability |
The capabilities of the promise for which this record provides a reaction handler. |
| [[Type]] |
Either "Fulfill" or "Reject".
|
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 |
25.6.1.3 CreateResolvingFunctions ( promise )
When CreateResolvingFunctions is performed with argument promise, the following steps are taken:
- Let alreadyResolved be a new
Record { [[Value]]:false }. - Let stepsResolve be the algorithm steps defined in Promise Resolve Functions (
25.6.1.3.2 ). - Let resolve be
CreateBuiltinFunction (stepsResolve, « [[Promise]], [[AlreadyResolved]] »). Set resolve.[[Promise]] to promise.Set resolve.[[AlreadyResolved]] to alreadyResolved.- Let stepsReject be the algorithm steps defined in Promise Reject Functions (
25.6.1.3.1 ). - Let reject be
CreateBuiltinFunction (stepsReject, « [[Promise]], [[AlreadyResolved]] »). Set reject.[[Promise]] to promise.Set reject.[[AlreadyResolved]] to alreadyResolved.- Return a new
Record { [[Resolve]]: resolve, [[Reject]]: reject }.
25.6.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 F is called with argument reason, the following steps are taken:
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 length property of a promise reject function is 1.
25.6.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 F is called with argument resolution, the following steps are taken:
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
- Perform
EnqueueJob ("PromiseJobs",PromiseResolveThenableJob , « promise, resolution, thenAction »). - Return
undefined .
The length property of a promise resolve function is 1.
25.6.1.4 FulfillPromise ( promise, value )
When the FulfillPromise abstract operation is called with arguments promise and value, the following steps are taken:
Assert : The value of promise.[[PromiseState]] is"pending".- Let reactions be promise.[[PromiseFulfillReactions]].
Set promise.[[PromiseResult]] to value.Set promise.[[PromiseFulfillReactions]] toundefined .Set promise.[[PromiseRejectReactions]] toundefined .Set promise.[[PromiseState]] to"fulfilled".- Return
TriggerPromiseReactions (reactions, value).
25.6.1.5 NewPromiseCapability ( C )
The abstract operation NewPromiseCapability takes a Promise
- If
IsConstructor (C) isfalse , throw aTypeError exception. - NOTE: C is assumed to be a
constructor function that supports the parameter conventions of thePromiseconstructor (see25.6.3.1 ). - Let promiseCapability be a new PromiseCapability { [[Promise]]:
undefined , [[Resolve]]:undefined , [[Reject]]:undefined }. - Let steps be the algorithm steps defined in
GetCapabilitiesExecutor Functions . - Let executor be
CreateBuiltinFunction (steps, « [[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
25.6.1.5.1 GetCapabilitiesExecutor Functions
A GetCapabilitiesExecutor function is an anonymous built-in function that has a [[Capability]] internal slot.
When a GetCapabilitiesExecutor function F is called with arguments resolve and reject, the following steps are taken:
Assert : F has a [[Capability]] internal slot whose value is a PromiseCapabilityRecord .- 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 length property of a GetCapabilitiesExecutor function is 2.
25.6.1.6 IsPromise ( x )
The abstract operation IsPromise checks for the promise brand on an object.
- If
Type (x) is not Object, returnfalse . - If x does not have a [[PromiseState]] internal slot, return
false . - Return
true .
25.6.1.7 RejectPromise ( promise, reason )
When the RejectPromise abstract operation is called with arguments promise and reason, the following steps are taken:
Assert : The value of promise.[[PromiseState]] is"pending".- Let reactions be promise.[[PromiseRejectReactions]].
Set promise.[[PromiseResult]] to reason.Set promise.[[PromiseFulfillReactions]] toundefined .Set promise.[[PromiseRejectReactions]] toundefined .Set promise.[[PromiseState]] to"rejected".- If promise.[[PromiseIsHandled]] is
false , performHostPromiseRejectionTracker (promise,"reject"). - Return
TriggerPromiseReactions (reactions, reason).
25.6.1.8 TriggerPromiseReactions ( reactions, argument )
The abstract operation TriggerPromiseReactions takes a collection of PromiseReactionRecords and enqueues a new Job for each record. Each such Job processes the [[Type]] and [[Handler]] of the PromiseReactionRecord, and if the [[Handler]] is a function, calls it passing the given argument. If the [[Handler]] is
- For each reaction in reactions, in original insertion order, do
- Perform
EnqueueJob ("PromiseJobs",PromiseReactionJob , « reaction, argument »).
- Perform
- Return
undefined .
25.6.1.9 HostPromiseRejectionTracker ( promise, operation )
HostPromiseRejectionTracker is an implementation-defined abstract operation that allows host environments to track promise rejections.
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 "handle", an implementation should not hold a reference to promise in a way that would interfere with garbage collection. An implementation may hold a reference to promise if operation is "reject", since it is expected that rejections will be rare and not on hot code paths.
25.6.2 Promise Jobs
25.6.2.1 PromiseReactionJob ( reaction, argument )
The job PromiseReactionJob with parameters reaction and argument applies the appropriate handler to the incoming value, and uses the handler's return value to resolve or reject the derived promise associated with that handler.
Assert : reaction is a PromiseReactionRecord .- Let promiseCapability be reaction.[[Capability]].
- Let type be reaction.[[Type]].
- Let handler be reaction.[[Handler]].
- If handler is
undefined , then- If type is
"Fulfill", let handlerResult beNormalCompletion (argument). - Else,
Assert : type is"Reject".- Let handlerResult be
ThrowCompletion (argument).
- If type is
- Else, let handlerResult be
Call (handler,undefined , « argument »). - 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).
25.6.2.2 PromiseResolveThenableJob ( promiseToResolve, thenable, then )
The job PromiseResolveThenableJob with parameters promiseToResolve, thenable, and then performs the following steps:
- Let resolvingFunctions be
CreateResolvingFunctions (promiseToResolve). - Let thenCallResult be
Call (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).
This Job uses the supplied thenable and its then method to resolve the given promise. This process must take place as a Job to ensure that the evaluation of the then method occurs after evaluation of any surrounding code has completed.
25.6.3 The Promise Constructor
The Promise
- is the intrinsic object
%Promise% . - is the initial value of the
Promiseproperty 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 specifiedPromisebehaviour must include asupercall to thePromiseconstructor to create and initialize the subclass instance with the internal state necessary to support thePromiseandPromise.prototypebuilt-in methods.
25.6.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,"%PromisePrototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »). Set promise.[[PromiseState]] to"pending".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
25.6.4 Properties of the Promise Constructor
The Promise
- has a [[Prototype]] internal slot whose value is the intrinsic object
%FunctionPrototype% . - has the following properties:
25.6.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. - If
Type (C) is not Object, throw aTypeError exception. - Let promiseCapability be ?
NewPromiseCapability (C). - Let iteratorRecord be
GetIterator (iterable). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
PerformPromiseAll (iteratorRecord, C, promiseCapability). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , let result beIteratorClose (iteratorRecord, result). IfAbruptRejectPromise (result, promiseCapability).
- If iteratorRecord.[[Done]] is
- Return
Completion (result).
This function is the %Promise_all% intrinsic object.
The all function requires its Promise
25.6.4.1.1 Runtime Semantics: PerformPromiseAll ( iteratorRecord, constructor, resultCapability )
When the PerformPromiseAll abstract operation is called with arguments iteratorRecord, constructor, and resultCapability, the following steps are taken:
Assert : constructor is aconstructor function.Assert : resultCapability is a PromiseCapabilityRecord .- Let values be a new empty
List . - Let remainingElementsCount be a new
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 ?
Invoke (constructor,"resolve", « nextValue »). - Let steps be the algorithm steps defined in
.Promise.allResolve Element Functions - Let resolveElement be
CreateBuiltinFunction (steps, « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »). Set resolveElement.[[AlreadyCalled]] to a newRecord { [[Value]]:false }.Set resolveElement.[[Index]] to index.Set resolveElement.[[Values]] to values.Set resolveElement.[[Capability]] to resultCapability.Set resolveElement.[[RemainingElements]] to remainingElementsCount.Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.- Perform ?
Invoke (nextPromise,"then", « resolveElement, resultCapability.[[Reject]] »). Set index to index + 1.
- Let next be
25.6.4.1.2 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 F is called with argument x, the following steps are taken:
- 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]].
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 length property of a Promise.all resolve element function is 1.
25.6.4.2 Promise.prototype
The initial value of Promise.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
25.6.4.3 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. - If
Type (C) is not Object, throw aTypeError exception. - Let promiseCapability be ?
NewPromiseCapability (C). - Let iteratorRecord be
GetIterator (iterable). IfAbruptRejectPromise (iteratorRecord, promiseCapability).- Let result be
PerformPromiseRace (iteratorRecord, C, promiseCapability). - If result is an
abrupt completion , then- If iteratorRecord.[[Done]] is
false , let result beIteratorClose (iterator, 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 Promise resolve method.
25.6.4.3.1 Runtime Semantics: PerformPromiseRace ( iteratorRecord, constructor, resultCapability )
When the PerformPromiseRace abstract operation is called with arguments iteratorRecord, constructor, and resultCapability, the following steps are taken:
Assert : constructor is aconstructor function.Assert : resultCapability is a PromiseCapabilityRecord .- 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 ?
Invoke (constructor,"resolve", « nextValue »). - Perform ?
Invoke (nextPromise,"then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
- Let next be
25.6.4.4 Promise.reject ( r )
The reject function returns a new promise rejected with the passed argument.
- Let C be the
this value. - If
Type (C) is not Object, throw aTypeError exception. - Let promiseCapability be ?
NewPromiseCapability (C). - Perform ?
Call (promiseCapability.[[Reject]],undefined , « r »). - Return promiseCapability.[[Promise]].
This function is the %Promise_reject% intrinsic object.
The reject function expects its Promise
25.6.4.5 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).
This function is the %Promise_resolve% intrinsic object.
The resolve function expects its Promise
25.6.4.5.1 PromiseResolve ( C, x )
The abstract operation PromiseResolve, given a
25.6.4.6 get Promise [ @@species ]
Promise[@@species] is an
- Return the
this value.
The value of the name property of this function is "get [Symbol.species]".
Promise prototype methods normally use their this object's
25.6.5 Properties of the Promise Prototype Object
The Promise prototype object:
- is the intrinsic object
%PromisePrototype% . - has a [[Prototype]] internal slot whose value is the intrinsic object
%ObjectPrototype% . - is an ordinary object.
- does not have a [[PromiseState]] internal slot or any of the other internal slots of Promise instances.
25.6.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 »).
25.6.5.2 Promise.prototype.constructor
The initial value of Promise.prototype.constructor is the intrinsic object
25.6.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 thenFinally be
CreateBuiltinFunction (stepsThenFinally, « [[Constructor]], [[OnFinally]] »). Set thenFinally.[[Constructor]] to C.Set thenFinally.[[OnFinally]] to onFinally.- Let stepsCatchFinally be the algorithm steps defined in
Catch Finally Functions . - Let catchFinally be
CreateBuiltinFunction (stepsCatchFinally, « [[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 »).
25.6.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 F is called with argument value, the following steps are taken:
- 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 length property of a Then Finally function is
25.6.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 F is called with argument reason, the following steps are taken:
- 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 length property of a Catch Finally function is
25.6.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).
This function is the %PromiseProto_then% intrinsic object.
25.6.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected, resultCapability )
The abstract operation PerformPromiseThen performs the “then” operation on promise using onFulfilled and onRejected as its settlement actions. The result is resultCapability's promise.
Assert :IsPromise (promise) istrue .Assert : resultCapability is a PromiseCapabilityRecord .- If
IsCallable (onFulfilled) isfalse , thenSet onFulfilled toundefined .
- If
IsCallable (onRejected) isfalse , thenSet onRejected toundefined .
- Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]:
"Fulfill", [[Handler]]: onFulfilled }. - Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]:
"Reject", [[Handler]]: onRejected }. - If promise.[[PromiseState]] is
"pending", then - Else if promise.[[PromiseState]] is
"fulfilled", then- Let value be promise.[[PromiseResult]].
- Perform
EnqueueJob ("PromiseJobs",PromiseReactionJob , « fulfillReaction, value »).
- Else,
Assert : The value of promise.[[PromiseState]] is"rejected".- Let reason be promise.[[PromiseResult]].
- If promise.[[PromiseIsHandled]] is
false , performHostPromiseRejectionTracker (promise,"handle"). - Perform
EnqueueJob ("PromiseJobs",PromiseReactionJob , « rejectReaction, reason »).
Set promise.[[PromiseIsHandled]] totrue .- Return resultCapability.[[Promise]].
25.6.5.5 Promise.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "Promise".
This property has the attributes { [[Writable]]:
25.6.6 Properties of Promise Instances
Promise instances are ordinary objects that inherit properties from the Promise prototype object (the intrinsic,
| Internal Slot | Description |
|---|---|
| [[PromiseState]] |
A String value that governs how a promise will react to incoming calls to its then method. The possible values are: "pending", "fulfilled", and "rejected".
|
| [[PromiseResult]] |
The value with which the promise has been fulfilled or rejected, if any. Only meaningful if [[PromiseState]] is not "pending".
|
| [[PromiseFulfillReactions]] |
A "pending" state to the "fulfilled" state.
|
| [[PromiseRejectReactions]] |
A "pending" state to the "rejected" state.
|
| [[PromiseIsHandled]] | A boolean indicating whether the promise has ever had a fulfillment or rejection handler; used in unhandled rejection tracking. |
25.7 AsyncFunction Objects
AsyncFunction objects are functions that are usually created by evaluating
25.7.1 The AsyncFunction Constructor
The AsyncFunction
- is the intrinsic object
%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 theAsyncFunctionconstructor to create and initialize a subclass instance with the internal slots necessary for built-in async function behaviour.
25.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 .
25.7.2 Properties of the AsyncFunction Constructor
The AsyncFunction
- is a standard built-in
function object that inherits from theFunctionconstructor . - has a [[Prototype]] internal slot whose value is the intrinsic object
%Function% . - has a
nameproperty whose value is"AsyncFunction". - has the following properties:
25.7.2.1 AsyncFunction.length
This is a
25.7.2.2 AsyncFunction.prototype
The initial value of AsyncFunction.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
25.7.3 Properties of the AsyncFunction Prototype Object
The AsyncFunction prototype object:
- 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 27 . - is the value of the
prototypeproperty of the intrinsic object%AsyncFunction% . - is the intrinsic object
%AsyncFunctionPrototype% . - has a [[Prototype]] internal slot whose value is the intrinsic object
%FunctionPrototype% .
25.7.3.1 AsyncFunction.prototype.constructor
The initial value of AsyncFunction.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.7.3.2 AsyncFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the string value "AsyncFunction".
This property has the attributes { [[Writable]]:
25.7.4 AsyncFunction Instances
Every AsyncFunction instance is an ECMAScript "async". AsyncFunction instances are not constructors and do not have a [[Construct]] internal method. AsyncFunction instances do not have a prototype property as they are not constructable.
Each AsyncFunction instance has the following own properties:
25.7.4.1 length
The specification for the length property of Function instances given in
25.7.4.2 name
The specification for the name property of Function instances given in
25.7.5 Async Functions Abstract Operations
25.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody )
- Let runningContext be the
running execution context . - Let asyncContext be a copy of runningContext.
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, the step 3.g above.- Return.