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 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 value of the [[Prototype]] internal slot of the
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.2 GeneratorFunction Objects
GeneratorFunction objects are functions that are usually created by evaluating
25.2.1 The GeneratorFunction Constructor
The GeneratorFunction constructor is the GeneratorFunction is called as a function rather than as a constructor, it creates and initializes a new GeneratorFunction object. Thus the function call GeneratorFunction (…) is equivalent to the object creation expression new GeneratorFunction (…) with the same arguments.
GeneratorFunction is designed to be subclassable. It may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified GeneratorFunction behaviour must include a super call to the GeneratorFunction constructor to create and initialize subclass instances with the internal slots necessary for built-in GeneratorFunction behaviour. All ECMAScript syntactic forms for defining generator function objects create direct instances of GeneratorFunction. There is no syntactic means to create instances of GeneratorFunction subclasses.
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 constructor is a standard built-in function object that inherits from the Function constructor. The value of the [[Prototype]] internal slot of the GeneratorFunction constructor is the intrinsic object
The value of the [[Extensible]] internal slot of the GeneratorFunction constructor is
The value of the name property of the GeneratorFunction is "GeneratorFunction".
The GeneratorFunction constructor has the following properties:
25.2.2.1 GeneratorFunction.length
This is a data property with a value of 1. This property has the attributes { [[Writable]]:
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. It is not a function object and does not have an [[ECMAScriptCode]] internal slot or any other of the internal slots listed in
The value of the [[Prototype]] internal slot of the GeneratorFunction prototype object is the
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 function object and has the internal slots listed in "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 function object is invoked using [[Call]].
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 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.3.1 Properties of Generator Prototype
The Generator prototype object is the prototype property of the
The Generator prototype is an ordinary object. It is not a Generator instance and does not have a [[GeneratorState]] internal slot.
The value of the [[Prototype]] internal slot of the Generator prototype object is the intrinsic object
All Generator instances indirectly inherit properties of the Generator prototype object.
25.3.1.1 Generator.prototype.constructor
The initial value of Generator.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.3.1.2 Generator.prototype.next ( value )
The next method performs the following steps:
- Let g be the
this value. - Return ?
GeneratorResume (g, value).
25.3.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.3.1.4 Generator.prototype.throw ( exception )
The throw method performs the following steps:
- Let g be the
this value. - Let C be
Completion {[[Type]]:throw , [[Value]]: exception, [[Target]]:empty }. - Return ?
GeneratorResumeAbrupt (g, C).
25.3.1.5 Generator.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "Generator".
This property has the attributes { [[Writable]]:
25.3.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.3.3 Generator Abstract Operations
25.3.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.3.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.3.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.3.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.3.3.5 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.
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.4 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.4.1 Promise Abstract Operations
25.4.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 function object | The function that is used to resolve the given promise object. |
| [[Reject]] | A function object | The function that is used to reject the given promise object. |
25.4.1.1.1 IfAbruptRejectPromise ( value, capability )
IfAbruptRejectPromise is a short hand 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.4.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 function object or |
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.4.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 resolve be a new built-in function object as defined in Promise Resolve Functions (
25.4.1.3.2 ). Set resolve.[[Promise]] to promise.Set resolve.[[AlreadyResolved]] to alreadyResolved.- Let reject be a new built-in function object as defined in Promise Reject Functions (
25.4.1.3.1 ). Set reject.[[Promise]] to promise.Set reject.[[AlreadyResolved]] to alreadyResolved.- Return a new
Record { [[Resolve]]: resolve, [[Reject]]: reject }.
25.4.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.4.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.4.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.4.1.5 NewPromiseCapability ( C )
The abstract operation NewPromiseCapability takes a constructor function, and attempts to use that constructor function in the fashion of the built-in Promise constructor to create a Promise object and extract its resolve and reject functions. The promise plus the resolve and reject functions are used to initialize a new PromiseCapability
- If
IsConstructor (C) isfalse , throw aTypeError exception. - NOTE: C is assumed to be a constructor function that supports the parameter conventions of the
Promiseconstructor (see25.4.3.1 ). - Let promiseCapability be a new PromiseCapability { [[Promise]]:
undefined , [[Resolve]]:undefined , [[Reject]]:undefined }. - Let executor be a new built-in function object as defined in
GetCapabilitiesExecutor Functions . 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 constructor that calls a passed executor function argument in the same way as the Promise constructor. It is used to generalize static methods of the Promise constructor to any subclass.
25.4.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.4.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.4.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.4.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.4.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.4.2 Promise Jobs
25.4.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
Completion {[[Type]]:throw , [[Value]]: argument, [[Target]]:empty }.
- 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.4.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.4.3 The Promise Constructor
The Promise constructor is the Promise property of the Promise is not intended to be called as a function and will throw an exception when called in that manner.
The Promise constructor is designed to be subclassable. It may be used as the value in an extends clause of a class definition. Subclass constructors that intend to inherit the specified Promise behaviour must include a super call to the Promise constructor to create and initialize the subclass instance with the internal state necessary to support the Promise and Promise.prototype built-in methods.
25.4.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 function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object. The executor is called with two arguments: resolve and reject. These are functions that may be used by the executor function to report eventual completion or failure of the deferred computation. Returning from the executor function does not mean that the deferred action has been completed but only that the request to eventually perform the deferred action has been accepted.
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 constructor have the capability to actually resolve and reject the associated promise. Subclasses may have different constructor behaviour that passes in customized values for resolve and reject.
25.4.4 Properties of the Promise Constructor
The value of the [[Prototype]] internal slot of the Promise constructor is the intrinsic object
The Promise constructor has the following properties:
25.4.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 iterator be
GetIterator (iterable). IfAbruptRejectPromise (iterator, promiseCapability).- Let iteratorRecord be
Record { [[Iterator]]: iterator, [[Done]]:false }. - Let result be
PerformPromiseAll (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).
The all function requires its Promise constructor.
25.4.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 a constructor 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.[[Iterator]]). - 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 resolveElement be a new built-in function object as defined in
.Promise.allResolve Element Functions 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.4.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.4.4.2 Promise.prototype
The initial value of Promise.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
25.4.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 iterator be
GetIterator (iterable). IfAbruptRejectPromise (iterator, promiseCapability).- Let iteratorRecord be
Record { [[Iterator]]: iterator, [[Done]]:false }. - 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 constructor. It also expects that its resolve method.
25.4.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 a constructor function.Assert : resultCapability is a PromiseCapabilityRecord .- Repeat,
- Let next be
IteratorStep (iteratorRecord.[[Iterator]]). - 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.4.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]].
The reject function expects its Promise constructor.
25.4.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 constructor.
- Let C be the
this value. - If
Type (C) is not Object, throw aTypeError exception. - If
IsPromise (x) istrue , then - Let promiseCapability be ?
NewPromiseCapability (C). - Perform ?
Call (promiseCapability.[[Resolve]],undefined , « x »). - Return promiseCapability.[[Promise]].
The resolve function expects its Promise constructor.
25.4.4.6 get Promise [ @@species ]
Promise[@@species] is an accessor property whose set accessor function is
- 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 constructor to create a derived object. However, a subclass constructor may over-ride that default behaviour by redefining its @@species property.
25.4.5 Properties of the Promise Prototype Object
The Promise prototype object is the intrinsic object
25.4.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.4.5.2 Promise.prototype.constructor
The initial value of Promise.prototype.constructor is the intrinsic object
25.4.5.3 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).
25.4.5.3.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.4.5.4 Promise.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the String value "Promise".
This property has the attributes { [[Writable]]:
25.4.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.5 AsyncFunction Objects
AsyncFunction objects are functions that are usually created by evaluating
25.5.1 The AsyncFunction Constructor
The AsyncFunction constructor is the Function. When AsyncFunction is called as a function rather than as a constructor, it creates and initializes a new AsyncFunction object. Thus the function call AsyncFunction(…) is equivalent to the object creation expression new AsyncFunction(…) with the same arguments.
The AsyncFunction constructor is designed to be subclassable. It may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified AsyncFunction behaviour must include a super call to the AsyncFunction constructor to create and initialize a subclass instance with the internal slots necessary for built-in async function behaviour.
25.5.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.5.2 Properties of the AsyncFunction Constructor
The AsyncFunction constructor is a standard built-in function object that inherits from the Function constructor. The value of the [[Prototype]] internal slot of the AsyncFunction constructor is the intrinsic object
The value of the [[Extensible]] internal slot of the AsyncFunction constructor is
The value of the
The AsyncFunction constructor has the following properties:
25.5.2.1 AsyncFunction.length
This is a data property with a value of 1. This property has the attributes { [[Writable]]:
25.5.2.2 AsyncFunction.prototype
The initial value of AsyncFunction.prototype is the intrinsic object
This property has the attributes { [[Writable]]:
25.5.3 Properties of the AsyncFunction Prototype Object
The AsyncFunction prototype object is an ordinary object. It is not a function object and does not have an [[ECMAScriptCode]] internal slot or any other of the internal slots listed in
The value of the [[Prototype]] internal slot of the AsyncFunction prototype object is the
25.5.3.1 AsyncFunction.prototype.constructor
The initial value of AsyncFunction.prototype.constructor is the intrinsic object
This property has the attributes { [[Writable]]:
25.5.3.2 AsyncFunction.prototype [ @@toStringTag ]
The initial value of the @@toStringTag property is the string value "AsyncFunction".
This property has the attributes { [[Writable]]:
25.5.4 AsyncFunction Instances
Every AsyncFunction instance is an ECMAScript function object and has the internal slots listed in "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.5.4.1 length
The specification for the length property of Function instances given in
25.5.4.2 name
The specification for the name property of Function instances given in
25.5.5 Async Functions Abstract Operations
25.5.5.1 AsyncFunctionCreate ( kind, parameters, body, Scope, Strict )
The abstract operation AsyncFunctionCreate requires the arguments: kind which is one of (
- Let functionPrototype be the intrinsic object
%AsyncFunctionPrototype% .
25.5.5.2 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 areAsyncFunctionAwait or, if the async function doesn't await anything, the step 3.g above.- Return.
25.5.5.3 AsyncFunctionAwait ( value )
- Let asyncContext be the
running execution context . - Let promiseCapability be !
NewPromiseCapability (%Promise% ). - Let resolveResult be !
Call (promiseCapability.[[Resolve]],undefined , « value »). - Let onFulfilled be a new built-in function object as defined in
AsyncFunction Awaited Fulfilled . - Let onRejected be a new built-in function object as defined in
AsyncFunction Awaited Rejected . Set onFulfilled.[[AsyncContext]] to asyncContext.Set onRejected.[[AsyncContext]] to asyncContext.- Let throwawayCapability be !
NewPromiseCapability (%Promise% ). Set throwawayCapability.[[Promise]].[[PromiseIsHandled]] totrue .- Perform !
PerformPromiseThen (promiseCapability.[[Promise]], onFulfilled, onRejected, throwawayCapability). - Remove asyncContext 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 asyncContext such that when evaluation is resumed with aCompletion resumptionValue the following steps will be performed:- Return resumptionValue.
- Return.
25.5.5.4 AsyncFunction Awaited Fulfilled
An AsyncFunction Awaited Fulfilled function is an anonymous built-in function that has an [[AsyncContext]] internal slot. The value of the [[AsyncContext]] internal slot is the
When an AsyncFunction Awaited Fulfilled function F is called with argument value, the following steps are taken:
- Let asyncContext be F.[[AsyncContext]].
- 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 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 reach this step, asyncContext has already been removed from theexecution context stack and prevContext is the currentlyrunning execution context .- Return
Completion (result).
25.5.5.5 AsyncFunction Awaited Rejected
An AsyncFunction Awaited Rejected function is an anonymous built-in function that has an [[AsyncContext]] internal slot. The value of the [[AsyncContext]] internal slot is the
When an AsyncFunction Awaited Rejected function F is called with argument reason, the following steps are taken:
- Let asyncContext be F.[[AsyncContext]].
- 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 using
Completion {[[Type]]:throw , [[Value]]: reason, [[Target]]:empty } as the result of the operation that suspended it. Let result be the value returned by the resumed computation. Assert : When we reach this step, asyncContext has already been removed from theexecution context stack and prevContext is the currentlyrunning execution context .- Return
Completion (result).