27 Control Abstraction Objects

27.1 Iteration

27.1.1 Common Iteration Interfaces

An interface is a set of property keys whose associated values match a specific specification. Any object that provides all the properties as described by an interface's specification conforms to that interface. An interface is not represented by a distinct object. There may be many separately implemented objects that conform to any interface. An individual object may conform to multiple interfaces.

27.1.1.1 The Iterable Interface

The Iterable interface includes the property described in Table 66:

Table 66: Iterable Interface Required Properties
Property Value Requirements
@@iterator A function that returns an Iterator object. The returned object must conform to the Iterator interface.

27.1.1.2 The Iterator Interface

An object that implements the Iterator interface must include the property in Table 67. Such objects may also implement the properties in Table 68.

Table 67: Iterator Interface Required Properties
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 true, then all subsequent calls to the next method of that object should also return an IteratorResult object whose "done" property is true. However, this requirement is not enforced.
Note 1

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.

Table 68: Iterator Interface Optional Properties
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 true, and a "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 true.
Note 2

Typically callers of these methods should check for their existence before invoking them. Certain ECMAScript language features including for-of, yield*, and array destructuring call these methods after performing an existence check. Most ECMAScript library functions that accept Iterable objects as arguments also conditionally call them.

27.1.1.3 The AsyncIterable Interface

The AsyncIterable interface includes the properties described in Table 69:

Table 69: AsyncIterable Interface Required Properties
Property Value Requirements
@@asyncIterator A function that returns an AsyncIterator object. The returned object must conform to the AsyncIterator interface.

27.1.1.4 The AsyncIterator Interface

An object that implements the AsyncIterator interface must include the properties in Table 70. Such objects may also implement the properties in Table 71.

Table 70: AsyncIterator Interface Required Properties
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 next method of an AsyncIterator has returned a promise for an IteratorResult object whose "done" property is true, then all subsequent calls to the next method of that object should also return a promise for an IteratorResult object whose "done" property is true. However, this requirement is not enforced.

Additionally, the IteratorResult object that serves as a fulfillment value should have a "value" property whose value is not a promise (or "thenable"). However, this requirement is also not enforced.

Note 1

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.

Table 71: AsyncIterator Interface Optional Properties
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 next method calls to the AsyncIterator. The returned promise will fulfill with an IteratorResult object which will typically have a "done" property whose value is true, and a "value" property with the value passed as the argument of the return method. However, this requirement is not enforced.

Additionally, the IteratorResult object that serves as a fulfillment value should have a "value" property whose value is not a promise (or "thenable"). If the argument value is used in the typical manner, then if it is a rejected promise, a promise rejected with the same reason should be returned; if it is a fulfilled promise, then its fulfillment value should be used as the "value" property of the returned promise's IteratorResult object fulfillment value. However, these requirements are also not enforced.

"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 "done" property whose value is true. Additionally, it should have a "value" property whose value is not a promise (or "thenable"), but this requirement is not enforced.

Note 2

Typically callers of these methods should check for their existence before invoking them. Certain ECMAScript language features including for-await-of and yield* call these methods after performing an existence check.

27.1.1.5 The IteratorResult Interface

The IteratorResult interface includes the properties listed in Table 72:

Table 72: IteratorResult Interface Properties
Property Value Requirements
"done" Either true or false. This is the result status of an iterator next method call. If the end of the iterator was reached "done" is true. If the end was not reached "done" is false and a value is available. If a "done" property (either own or inherited) does not exist, it is considered to have the value false.
"value" Any ECMAScript language value. If done is false, this is the current iteration element value. If done is true, this is the return value of the iterator, if it supplied one. If the iterator does not have a return value, "value" is undefined. In that case, the "value" property may be absent from the conforming object if it does not inherit an explicit "value" property.

27.1.2 The %IteratorPrototype% Object

The %IteratorPrototype% object:

Note

All objects defined in this specification that implement the Iterator interface also inherit from %IteratorPrototype%. ECMAScript code may also define objects that inherit from %IteratorPrototype%. The %IteratorPrototype% object provides a place where additional methods that are applicable to all iterator objects may be added.

The following expression is one way that ECMAScript code can access the %IteratorPrototype% object:

Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))

27.1.2.1 %IteratorPrototype% [ @@iterator ] ( )

The following steps are taken:

  1. Return the this value.

The value of the "name" property of this function is "[Symbol.iterator]".

27.1.3 The %AsyncIteratorPrototype% Object

The %AsyncIteratorPrototype% object:

Note

All objects defined in this specification that implement the AsyncIterator interface also inherit from %AsyncIteratorPrototype%. ECMAScript code may also define objects that inherit from %AsyncIteratorPrototype%. The %AsyncIteratorPrototype% object provides a place where additional methods that are applicable to all async iterator objects may be added.

27.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )

The following steps are taken:

  1. Return the this value.

The value of the "name" property of this function is "[Symbol.asyncIterator]".

27.1.4 Async-from-Sync Iterator Objects

An Async-from-Sync Iterator object is an async iterator that adapts a specific synchronous iterator. There is not a named constructor for Async-from-Sync Iterator objects. Instead, Async-from-Sync iterator objects are created by the CreateAsyncFromSyncIterator abstract operation as needed.

27.1.4.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )

The abstract operation CreateAsyncFromSyncIterator takes argument syncIteratorRecord. It is used to create an async iterator Record from a synchronous iterator Record. It performs the following steps when called:

  1. Let asyncIterator be ! OrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »).
  2. Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord.
  3. Let nextMethod be ! Get(asyncIterator, "next").
  4. Let iteratorRecord be the Record { [[Iterator]]: asyncIterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  5. Return iteratorRecord.

27.1.4.2 The %AsyncFromSyncIteratorPrototype% Object

The %AsyncFromSyncIteratorPrototype% object:

  • has properties that are inherited by all Async-from-Sync Iterator Objects.
  • is an ordinary object.
  • has a [[Prototype]] internal slot whose value is %AsyncIteratorPrototype%.
  • has the following properties:

27.1.4.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )

  1. Let O be the this value.
  2. Assert: Type(O) is Object and O has a [[SyncIteratorRecord]] internal slot.
  3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  4. Let syncIteratorRecord be O.[[SyncIteratorRecord]].
  5. If value is present, then
    1. Let result be IteratorNext(syncIteratorRecord, value).
  6. Else,
    1. Let result be IteratorNext(syncIteratorRecord).
  7. IfAbruptRejectPromise(result, promiseCapability).
  8. Return ! AsyncFromSyncIteratorContinuation(result, promiseCapability).

27.1.4.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )

  1. Let O be the this value.
  2. Assert: Type(O) is Object and O has a [[SyncIteratorRecord]] internal slot.
  3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
  5. Let return be GetMethod(syncIterator, "return").
  6. IfAbruptRejectPromise(return, promiseCapability).
  7. If return is undefined, then
    1. Let iterResult be ! CreateIterResultObject(value, true).
    2. Perform ! Call(promiseCapability.[[Resolve]], undefined, « iterResult »).
    3. Return promiseCapability.[[Promise]].
  8. If value is present, then
    1. Let result be Call(return, syncIterator, « value »).
  9. Else,
    1. Let result be Call(return, syncIterator).
  10. IfAbruptRejectPromise(result, promiseCapability).
  11. If Type(result) is not Object, then
    1. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
    2. Return promiseCapability.[[Promise]].
  12. Return ! AsyncFromSyncIteratorContinuation(result, promiseCapability).

27.1.4.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )

Note
In this specification, value is always provided, but is left optional for consistency with %AsyncFromSyncIteratorPrototype%.return ( [ value ] ).
  1. Let O be the this value.
  2. Assert: Type(O) is Object and O has a [[SyncIteratorRecord]] internal slot.
  3. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  4. Let syncIterator be O.[[SyncIteratorRecord]].[[Iterator]].
  5. Let throw be GetMethod(syncIterator, "throw").
  6. IfAbruptRejectPromise(throw, promiseCapability).
  7. If throw is undefined, then
    1. Perform ! Call(promiseCapability.[[Reject]], undefined, « value »).
    2. Return promiseCapability.[[Promise]].
  8. If value is present, then
    1. Let result be Call(throw, syncIterator, « value »).
  9. Else,
    1. Let result be Call(throw, syncIterator).
  10. IfAbruptRejectPromise(result, promiseCapability).
  11. If Type(result) is not Object, then
    1. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
    2. Return promiseCapability.[[Promise]].
  12. Return ! AsyncFromSyncIteratorContinuation(result, promiseCapability).

27.1.4.2.4 Async-from-Sync Iterator Value Unwrap Functions

An async-from-sync iterator value unwrap function is an anonymous built-in function that is used by AsyncFromSyncIteratorContinuation when processing the "value" property of an IteratorResult object, in order to wait for its value if it is a promise and re-package the result in a new "unwrapped" IteratorResult object. Each async-from-sync iterator value unwrap function has a [[Done]] internal slot.

When an async-from-sync iterator value unwrap function is called with argument value, the following steps are taken:

  1. Let F be the active function object.
  2. Return ! CreateIterResultObject(value, F.[[Done]]).

27.1.4.3 Properties of Async-from-Sync Iterator Instances

Async-from-Sync Iterator instances are ordinary objects that inherit properties from the %AsyncFromSyncIteratorPrototype% intrinsic object. Async-from-Sync Iterator instances are initially created with the internal slots listed in Table 73. Async-from-Sync Iterator instances are not directly observable from ECMAScript code.

Table 73: Internal Slots of Async-from-Sync Iterator Instances
Internal Slot Description
[[SyncIteratorRecord]] A Record, of the type returned by GetIterator, representing the original synchronous iterator which is being adapted.

27.1.4.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability )

The abstract operation AsyncFromSyncIteratorContinuation takes arguments result and promiseCapability (a PromiseCapability Record). It performs the following steps when called:

  1. Let done be IteratorComplete(result).
  2. IfAbruptRejectPromise(done, promiseCapability).
  3. Let value be IteratorValue(result).
  4. IfAbruptRejectPromise(value, promiseCapability).
  5. Let valueWrapper be PromiseResolve(%Promise%, value).
  6. IfAbruptRejectPromise(valueWrapper, promiseCapability).
  7. Let steps be the algorithm steps defined in Async-from-Sync Iterator Value Unwrap Functions.
  8. Let length be the number of non-optional parameters of the function definition in Async-from-Sync Iterator Value Unwrap Functions.
  9. Let onFulfilled be ! CreateBuiltinFunction(steps, length, "", « [[Done]] »).
  10. Set onFulfilled.[[Done]] to done.
  11. Perform ! PerformPromiseThen(valueWrapper, onFulfilled, undefined, promiseCapability).
  12. Return promiseCapability.[[Promise]].

27.2 Promise Objects

A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.

Any Promise object is in one of three mutually exclusive states: fulfilled, rejected, and pending:

  • A promise p is fulfilled if p.then(f, r) will immediately enqueue a Job to call the function f.
  • A promise p is rejected if p.then(f, r) will immediately enqueue a Job to call the function r.
  • A promise is pending if it is neither fulfilled nor rejected.

A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected.

A promise is resolved if it is settled or if it has been “locked in” to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is unresolved if it is not resolved. An unresolved promise is always in the pending state. A resolved promise may be pending, fulfilled or rejected.

27.2.1 Promise Abstract Operations

27.2.1.1 PromiseCapability Records

A PromiseCapability Record is a Record value used to encapsulate a promise object along with the functions that are capable of resolving or rejecting that promise object. PromiseCapability Records are produced by the NewPromiseCapability abstract operation.

PromiseCapability Records have the fields listed in Table 74.

Table 74: PromiseCapability Record Fields
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.

27.2.1.1.1 IfAbruptRejectPromise ( value, capability )

IfAbruptRejectPromise is a shorthand for a sequence of algorithm steps that use a PromiseCapability Record. An algorithm step of the form:

  1. IfAbruptRejectPromise(value, capability).

means the same thing as:

  1. If value is an abrupt completion, then
    1. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »).
    2. Return capability.[[Promise]].
  2. Else if value is a Completion Record, set value to value.[[Value]].

27.2.1.2 PromiseReaction Records

The PromiseReaction is a Record value used to store information about how a promise should react when it becomes resolved or rejected with a given value. PromiseReaction records are created by the PerformPromiseThen abstract operation, and are used by the Abstract Closure returned by NewPromiseReactionJob.

PromiseReaction records have the fields listed in Table 75.

Table 75: PromiseReaction Record Fields
Field Name Value Meaning
[[Capability]] A PromiseCapability Record, or undefined The capabilities of the promise for which this record provides a reaction handler.
[[Type]] Fulfill | Reject The [[Type]] is used when [[Handler]] is empty to allow for behaviour specific to the settlement type.
[[Handler]] A JobCallback Record | empty. 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 empty, a function that depends on the value of [[Type]] will be used instead.

27.2.1.3 CreateResolvingFunctions ( promise )

The abstract operation CreateResolvingFunctions takes argument promise. It performs the following steps when called:

  1. Let alreadyResolved be the Record { [[Value]]: false }.
  2. Let stepsResolve be the algorithm steps defined in Promise Resolve Functions.
  3. Let lengthResolve be the number of non-optional parameters of the function definition in Promise Resolve Functions.
  4. Let resolve be ! CreateBuiltinFunction(stepsResolve, lengthResolve, "", « [[Promise]], [[AlreadyResolved]] »).
  5. Set resolve.[[Promise]] to promise.
  6. Set resolve.[[AlreadyResolved]] to alreadyResolved.
  7. Let stepsReject be the algorithm steps defined in Promise Reject Functions.
  8. Let lengthReject be the number of non-optional parameters of the function definition in Promise Reject Functions.
  9. Let reject be ! CreateBuiltinFunction(stepsReject, lengthReject, "", « [[Promise]], [[AlreadyResolved]] »).
  10. Set reject.[[Promise]] to promise.
  11. Set reject.[[AlreadyResolved]] to alreadyResolved.
  12. Return the Record { [[Resolve]]: resolve, [[Reject]]: reject }.

27.2.1.3.1 Promise Reject Functions

A promise reject function is an anonymous built-in function that has [[Promise]] and [[AlreadyResolved]] internal slots.

When a promise reject function is called with argument reason, the following steps are taken:

  1. Let F be the active function object.
  2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  3. Let promise be F.[[Promise]].
  4. Let alreadyResolved be F.[[AlreadyResolved]].
  5. If alreadyResolved.[[Value]] is true, return undefined.
  6. Set alreadyResolved.[[Value]] to true.
  7. Return RejectPromise(promise, reason).

The "length" property of a promise reject function is 1𝔽.

27.2.1.3.2 Promise Resolve Functions

A promise resolve function is an anonymous built-in function that has [[Promise]] and [[AlreadyResolved]] internal slots.

When a promise resolve function is called with argument resolution, the following steps are taken:

  1. Let F be the active function object.
  2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  3. Let promise be F.[[Promise]].
  4. Let alreadyResolved be F.[[AlreadyResolved]].
  5. If alreadyResolved.[[Value]] is true, return undefined.
  6. Set alreadyResolved.[[Value]] to true.
  7. If SameValue(resolution, promise) is true, then
    1. Let selfResolutionError be a newly created TypeError object.
    2. Return RejectPromise(promise, selfResolutionError).
  8. If Type(resolution) is not Object, then
    1. Return FulfillPromise(promise, resolution).
  9. Let then be Get(resolution, "then").
  10. If then is an abrupt completion, then
    1. Return RejectPromise(promise, then.[[Value]]).
  11. Let thenAction be then.[[Value]].
  12. If IsCallable(thenAction) is false, then
    1. Return FulfillPromise(promise, resolution).
  13. Let thenJobCallback be HostMakeJobCallback(thenAction).
  14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback).
  15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  16. Return undefined.

The "length" property of a promise resolve function is 1𝔽.

27.2.1.4 FulfillPromise ( promise, value )

The abstract operation FulfillPromise takes arguments promise and value. It performs the following steps when called:

  1. Assert: The value of promise.[[PromiseState]] is pending.
  2. Let reactions be promise.[[PromiseFulfillReactions]].
  3. Set promise.[[PromiseResult]] to value.
  4. Set promise.[[PromiseFulfillReactions]] to undefined.
  5. Set promise.[[PromiseRejectReactions]] to undefined.
  6. Set promise.[[PromiseState]] to fulfilled.
  7. Return TriggerPromiseReactions(reactions, value).

27.2.1.5 NewPromiseCapability ( C )

The abstract operation NewPromiseCapability takes argument C. It attempts to use C as a constructor in the fashion of the built-in Promise constructor to create a Promise object and extract its resolve and reject functions. The Promise object plus the resolve and reject functions are used to initialize a new PromiseCapability Record. It performs the following steps when called:

  1. If IsConstructor(C) is false, throw a TypeError exception.
  2. NOTE: C is assumed to be a constructor function that supports the parameter conventions of the Promise constructor (see 27.2.3.1).
  3. Let promiseCapability be the PromiseCapability Record { [[Promise]]: undefined, [[Resolve]]: undefined, [[Reject]]: undefined }.
  4. Let steps be the algorithm steps defined in GetCapabilitiesExecutor Functions.
  5. Let length be the number of non-optional parameters of the function definition in GetCapabilitiesExecutor Functions.
  6. Let executor be ! CreateBuiltinFunction(steps, length, "", « [[Capability]] »).
  7. Set executor.[[Capability]] to promiseCapability.
  8. Let promise be ? Construct(C, « executor »).
  9. If IsCallable(promiseCapability.[[Resolve]]) is false, throw a TypeError exception.
  10. If IsCallable(promiseCapability.[[Reject]]) is false, throw a TypeError exception.
  11. Set promiseCapability.[[Promise]] to promise.
  12. Return promiseCapability.
Note

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.

27.2.1.5.1 GetCapabilitiesExecutor Functions

A GetCapabilitiesExecutor function is an anonymous built-in function that has a [[Capability]] internal slot.

When a GetCapabilitiesExecutor function is called with arguments resolve and reject, the following steps are taken:

  1. Let F be the active function object.
  2. Assert: F has a [[Capability]] internal slot whose value is a PromiseCapability Record.
  3. Let promiseCapability be F.[[Capability]].
  4. If promiseCapability.[[Resolve]] is not undefined, throw a TypeError exception.
  5. If promiseCapability.[[Reject]] is not undefined, throw a TypeError exception.
  6. Set promiseCapability.[[Resolve]] to resolve.
  7. Set promiseCapability.[[Reject]] to reject.
  8. Return undefined.

The "length" property of a GetCapabilitiesExecutor function is 2𝔽.

27.2.1.6 IsPromise ( x )

The abstract operation IsPromise takes argument x. It checks for the promise brand on an object. It performs the following steps when called:

  1. If Type(x) is not Object, return false.
  2. If x does not have a [[PromiseState]] internal slot, return false.
  3. Return true.

27.2.1.7 RejectPromise ( promise, reason )

The abstract operation RejectPromise takes arguments promise and reason. It performs the following steps when called:

  1. Assert: The value of promise.[[PromiseState]] is pending.
  2. Let reactions be promise.[[PromiseRejectReactions]].
  3. Set promise.[[PromiseResult]] to reason.
  4. Set promise.[[PromiseFulfillReactions]] to undefined.
  5. Set promise.[[PromiseRejectReactions]] to undefined.
  6. Set promise.[[PromiseState]] to rejected.
  7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject").
  8. Return TriggerPromiseReactions(reactions, reason).

27.2.1.8 TriggerPromiseReactions ( reactions, argument )

The abstract operation TriggerPromiseReactions takes arguments reactions (a List of PromiseReaction Records) and argument. It enqueues a new Job for each record in reactions. Each such Job processes the [[Type]] and [[Handler]] of the PromiseReaction Record, and if the [[Handler]] is not empty, calls it passing the given argument. If the [[Handler]] is empty, the behaviour is determined by the [[Type]]. It performs the following steps when called:

  1. For each element reaction of reactions, do
    1. Let job be NewPromiseReactionJob(reaction, argument).
    2. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  2. Return undefined.

27.2.1.9 HostPromiseRejectionTracker ( promise, operation )

The host-defined abstract operation HostPromiseRejectionTracker takes arguments promise (a Promise) and operation ("reject" or "handle"). It 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.

Note 1

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.

Note 2

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.

27.2.2 Promise Jobs

27.2.2.1 NewPromiseReactionJob ( reaction, argument )

The abstract operation NewPromiseReactionJob takes arguments reaction and argument. It returns a new Job Abstract Closure that 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. It performs the following steps when called:

  1. Let job be a new Job Abstract Closure with no parameters that captures reaction and argument and performs the following steps when called:
    1. Assert: reaction is a PromiseReaction Record.
    2. Let promiseCapability be reaction.[[Capability]].
    3. Let type be reaction.[[Type]].
    4. Let handler be reaction.[[Handler]].
    5. If handler is empty, then
      1. If type is Fulfill, let handlerResult be NormalCompletion(argument).
      2. Else,
        1. Assert: type is Reject.
        2. Let handlerResult be ThrowCompletion(argument).
    6. Else, let handlerResult be HostCallJobCallback(handler, undefined, « argument »).
    7. If promiseCapability is undefined, then
      1. Assert: handlerResult is not an abrupt completion.
      2. Return NormalCompletion(empty).
    8. Assert: promiseCapability is a PromiseCapability Record.
    9. If handlerResult is an abrupt completion, then
      1. Let status be Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »).
    10. Else,
      1. Let status be Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »).
    11. Return Completion(status).
  2. Let handlerRealm be null.
  3. If reaction.[[Handler]] is not empty, then
    1. Let getHandlerRealmResult be GetFunctionRealm(reaction.[[Handler]].[[Callback]]).
    2. If getHandlerRealmResult is a normal completion, set handlerRealm to getHandlerRealmResult.[[Value]].
    3. Else, set handlerRealm to the current Realm Record.
    4. NOTE: handlerRealm is never null unless the handler is undefined. When the handler is a revoked Proxy and no ECMAScript code runs, handlerRealm is used to create error objects.
  4. Return the Record { [[Job]]: job, [[Realm]]: handlerRealm }.

27.2.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )

The abstract operation NewPromiseResolveThenableJob takes arguments promiseToResolve, thenable, and then. It performs the following steps when called:

  1. Let job be a new Job Abstract Closure with no parameters that captures promiseToResolve, thenable, and then and performs the following steps when called:
    1. Let resolvingFunctions be CreateResolvingFunctions(promiseToResolve).
    2. Let thenCallResult be HostCallJobCallback(then, thenable, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »).
    3. If thenCallResult is an abrupt completion, then
      1. Let status be Call(resolvingFunctions.[[Reject]], undefined, « thenCallResult.[[Value]] »).
      2. Return Completion(status).
    4. Return Completion(thenCallResult).
  2. Let getThenRealmResult be GetFunctionRealm(then.[[Callback]]).
  3. If getThenRealmResult is a normal completion, let thenRealm be getThenRealmResult.[[Value]].
  4. Else, let thenRealm be the current Realm Record.
  5. NOTE: thenRealm is never null. When then.[[Callback]] is a revoked Proxy and no code runs, thenRealm is used to create error objects.
  6. Return the Record { [[Job]]: job, [[Realm]]: thenRealm }.
Note

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.

27.2.3 The Promise Constructor

The Promise constructor:

  • is %Promise%.
  • is the initial value of the "Promise" property of the global 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 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.

27.2.3.1 Promise ( executor )

When the Promise function is called with argument executor, the following steps are taken:

  1. If NewTarget is undefined, throw a TypeError exception.
  2. If IsCallable(executor) is false, throw a TypeError exception.
  3. Let promise be ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »).
  4. Set promise.[[PromiseState]] to pending.
  5. Set promise.[[PromiseFulfillReactions]] to a new empty List.
  6. Set promise.[[PromiseRejectReactions]] to a new empty List.
  7. Set promise.[[PromiseIsHandled]] to false.
  8. Let resolvingFunctions be CreateResolvingFunctions(promise).
  9. Let completion be Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »).
  10. If completion is an abrupt completion, then
    1. Perform ? Call(resolvingFunctions.[[Reject]], undefined, « completion.[[Value]] »).
  11. Return promise.
Note

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.

27.2.4 Properties of the Promise Constructor

The Promise constructor:

  • has a [[Prototype]] internal slot whose value is %Function.prototype%.
  • has the following properties:

27.2.4.1 Promise.all ( iterable )

The all function returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejects with the reason of the first passed promise that rejects. It resolves all elements of the passed iterable to promises as it runs this algorithm.

  1. Let C be the this value.
  2. Let promiseCapability be ? NewPromiseCapability(C).
  3. Let promiseResolve be GetPromiseResolve(C).
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. Let iteratorRecord be GetIterator(iterable).
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. Let result be PerformPromiseAll(iteratorRecord, C, promiseCapability, promiseResolve).
  8. If result is an abrupt completion, then
    1. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. Return Completion(result).
Note

The all function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

27.2.4.1.1 GetPromiseResolve ( promiseConstructor )

The abstract operation GetPromiseResolve takes argument promiseConstructor. It performs the following steps when called:

  1. Assert: IsConstructor(promiseConstructor) is true.
  2. Let promiseResolve be ? Get(promiseConstructor, "resolve").
  3. If IsCallable(promiseResolve) is false, throw a TypeError exception.
  4. Return promiseResolve.

27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAll takes arguments iteratorRecord, constructor, resultCapability (a PromiseCapability Record), and promiseResolve. It performs the following steps when called:

  1. Assert: IsConstructor(constructor) is true.
  2. Assert: IsCallable(promiseResolve) is true.
  3. Let values be a new empty List.
  4. Let remainingElementsCount be the Record { [[Value]]: 1 }.
  5. Let index be 0.
  6. Repeat,
    1. Let next be IteratorStep(iteratorRecord).
    2. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
    3. ReturnIfAbrupt(next).
    4. If next is false, then
      1. Set iteratorRecord.[[Done]] to true.
      2. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
      3. If remainingElementsCount.[[Value]] is 0, then
        1. Let valuesArray be ! CreateArrayFromList(values).
        2. Perform ? Call(resultCapability.[[Resolve]], undefined, « valuesArray »).
      4. Return resultCapability.[[Promise]].
    5. Let nextValue be IteratorValue(next).
    6. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
    7. ReturnIfAbrupt(nextValue).
    8. Append undefined to values.
    9. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
    10. Let steps be the algorithm steps defined in Promise.all Resolve Element Functions.
    11. Let length be the number of non-optional parameters of the function definition in Promise.all Resolve Element Functions.
    12. Let onFulfilled be ! CreateBuiltinFunction(steps, length, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
    13. Set onFulfilled.[[AlreadyCalled]] to false.
    14. Set onFulfilled.[[Index]] to index.
    15. Set onFulfilled.[[Values]] to values.
    16. Set onFulfilled.[[Capability]] to resultCapability.
    17. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
    18. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.
    19. Perform ? Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »).
    20. Set index to index + 1.

27.2.4.1.3 Promise.all Resolve Element Functions

A Promise.all resolve element function is an anonymous built-in function that is used to resolve a specific Promise.all element. Each Promise.all resolve element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.

When a Promise.all resolve element function is called with argument x, the following steps are taken:

  1. Let F be the active function object.
  2. If F.[[AlreadyCalled]] is true, return undefined.
  3. Set F.[[AlreadyCalled]] to true.
  4. Let index be F.[[Index]].
  5. Let values be F.[[Values]].
  6. Let promiseCapability be F.[[Capability]].
  7. Let remainingElementsCount be F.[[RemainingElements]].
  8. Set values[index] to x.
  9. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
  10. If remainingElementsCount.[[Value]] is 0, then
    1. Let valuesArray be ! CreateArrayFromList(values).
    2. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
  11. Return undefined.

The "length" property of a Promise.all resolve element function is 1𝔽.

27.2.4.2 Promise.allSettled ( iterable )

The allSettled function returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.

  1. Let C be the this value.
  2. Let promiseCapability be ? NewPromiseCapability(C).
  3. Let promiseResolve be GetPromiseResolve(C).
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. Let iteratorRecord be GetIterator(iterable).
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. Let result be PerformPromiseAllSettled(iteratorRecord, C, promiseCapability, promiseResolve).
  8. If result is an abrupt completion, then
    1. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. Return Completion(result).
Note

The allSettled function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord, constructor, resultCapability (a PromiseCapability Record), and promiseResolve. It performs the following steps when called:

  1. Assert: ! IsConstructor(constructor) is true.
  2. Assert: IsCallable(promiseResolve) is true.
  3. Let values be a new empty List.
  4. Let remainingElementsCount be the Record { [[Value]]: 1 }.
  5. Let index be 0.
  6. Repeat,
    1. Let next be IteratorStep(iteratorRecord).
    2. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
    3. ReturnIfAbrupt(next).
    4. If next is false, then
      1. Set iteratorRecord.[[Done]] to true.
      2. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
      3. If remainingElementsCount.[[Value]] is 0, then
        1. Let valuesArray be ! CreateArrayFromList(values).
        2. Perform ? Call(resultCapability.[[Resolve]], undefined, « valuesArray »).
      4. Return resultCapability.[[Promise]].
    5. Let nextValue be IteratorValue(next).
    6. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
    7. ReturnIfAbrupt(nextValue).
    8. Append undefined to values.
    9. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
    10. Let stepsFulfilled be the algorithm steps defined in Promise.allSettled Resolve Element Functions.
    11. Let lengthFulfilled be the number of non-optional parameters of the function definition in Promise.allSettled Resolve Element Functions.
    12. Let onFulfilled be ! CreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
    13. Let alreadyCalled be the Record { [[Value]]: false }.
    14. Set onFulfilled.[[AlreadyCalled]] to alreadyCalled.
    15. Set onFulfilled.[[Index]] to index.
    16. Set onFulfilled.[[Values]] to values.
    17. Set onFulfilled.[[Capability]] to resultCapability.
    18. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
    19. Let stepsRejected be the algorithm steps defined in Promise.allSettled Reject Element Functions.
    20. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.allSettled Reject Element Functions.
    21. Let onRejected be ! CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
    22. Set onRejected.[[AlreadyCalled]] to alreadyCalled.
    23. Set onRejected.[[Index]] to index.
    24. Set onRejected.[[Values]] to values.
    25. Set onRejected.[[Capability]] to resultCapability.
    26. Set onRejected.[[RemainingElements]] to remainingElementsCount.
    27. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.
    28. Perform ? Invoke(nextPromise, "then", « onFulfilled, onRejected »).
    29. Set index to index + 1.

27.2.4.2.2 Promise.allSettled Resolve Element Functions

A Promise.allSettled resolve element function is an anonymous built-in function that is used to resolve a specific Promise.allSettled element. Each Promise.allSettled resolve element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.

When a Promise.allSettled resolve element function is called with argument x, the following steps are taken:

  1. Let F be the active function object.
  2. Let alreadyCalled be F.[[AlreadyCalled]].
  3. If alreadyCalled.[[Value]] is true, return undefined.
  4. Set alreadyCalled.[[Value]] to true.
  5. Let index be F.[[Index]].
  6. Let values be F.[[Values]].
  7. Let promiseCapability be F.[[Capability]].
  8. Let remainingElementsCount be F.[[RemainingElements]].
  9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
  10. Perform ! CreateDataPropertyOrThrow(obj, "status", "fulfilled").
  11. Perform ! CreateDataPropertyOrThrow(obj, "value", x).
  12. Set values[index] to obj.
  13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
  14. If remainingElementsCount.[[Value]] is 0, then
    1. Let valuesArray be ! CreateArrayFromList(values).
    2. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
  15. Return undefined.

The "length" property of a Promise.allSettled resolve element function is 1𝔽.

27.2.4.2.3 Promise.allSettled Reject Element Functions

A Promise.allSettled reject element function is an anonymous built-in function that is used to reject a specific Promise.allSettled element. Each Promise.allSettled reject element function has [[Index]], [[Values]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.

When a Promise.allSettled reject element function is called with argument x, the following steps are taken:

  1. Let F be the active function object.
  2. Let alreadyCalled be F.[[AlreadyCalled]].
  3. If alreadyCalled.[[Value]] is true, return undefined.
  4. Set alreadyCalled.[[Value]] to true.
  5. Let index be F.[[Index]].
  6. Let values be F.[[Values]].
  7. Let promiseCapability be F.[[Capability]].
  8. Let remainingElementsCount be F.[[RemainingElements]].
  9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
  10. Perform ! CreateDataPropertyOrThrow(obj, "status", "rejected").
  11. Perform ! CreateDataPropertyOrThrow(obj, "reason", x).
  12. Set values[index] to obj.
  13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
  14. If remainingElementsCount.[[Value]] is 0, then
    1. Let valuesArray be ! CreateArrayFromList(values).
    2. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
  15. Return undefined.

The "length" property of a Promise.allSettled reject element function is 1𝔽.

27.2.4.3 Promise.any ( iterable )

The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError holding the rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.

  1. Let C be the this value.
  2. Let promiseCapability be ? NewPromiseCapability(C).
  3. Let promiseResolve be GetPromiseResolve(C).
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. Let iteratorRecord be GetIterator(iterable).
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. Let result be PerformPromiseAny(iteratorRecord, C, promiseCapability, promiseResolve).
  8. If result is an abrupt completion, then
    1. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. Return Completion(result).
Note

The any function requires its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAny takes arguments iteratorRecord, constructor, resultCapability (a PromiseCapability Record), and promiseResolve. It performs the following steps when called:

  1. Assert: ! IsConstructor(constructor) is true.
  2. Assert: ! IsCallable(promiseResolve) is true.
  3. Let errors be a new empty List.
  4. Let remainingElementsCount be the Record { [[Value]]: 1 }.
  5. Let index be 0.
  6. Repeat,
    1. Let next be IteratorStep(iteratorRecord).
    2. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
    3. ReturnIfAbrupt(next).
    4. If next is false, then
      1. Set iteratorRecord.[[Done]] to true.
      2. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
      3. If remainingElementsCount.[[Value]] is 0, then
        1. Let error be a newly created AggregateError object.
        2. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: ! CreateArrayFromList(errors) }).
        3. Return ThrowCompletion(error).
      4. Return resultCapability.[[Promise]].
    5. Let nextValue be IteratorValue(next).
    6. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
    7. ReturnIfAbrupt(nextValue).
    8. Append undefined to errors.
    9. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
    10. Let stepsRejected be the algorithm steps defined in Promise.any Reject Element Functions.
    11. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.any Reject Element Functions.
    12. Let onRejected be ! CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Errors]], [[Capability]], [[RemainingElements]] »).
    13. Set onRejected.[[AlreadyCalled]] to false.
    14. Set onRejected.[[Index]] to index.
    15. Set onRejected.[[Errors]] to errors.
    16. Set onRejected.[[Capability]] to resultCapability.
    17. Set onRejected.[[RemainingElements]] to remainingElementsCount.
    18. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.
    19. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »).
    20. Set index to index + 1.

27.2.4.3.2 Promise.any Reject Element Functions

A Promise.any reject element function is an anonymous built-in function that is used to reject a specific Promise.any element. Each Promise.any reject element function has [[Index]], [[Errors]], [[Capability]], [[RemainingElements]], and [[AlreadyCalled]] internal slots.

When a Promise.any reject element function is called with argument x, the following steps are taken:

  1. Let F be the active function object.
  2. If F.[[AlreadyCalled]] is true, return undefined.
  3. Set F.[[AlreadyCalled]] to true.
  4. Let index be F.[[Index]].
  5. Let errors be F.[[Errors]].
  6. Let promiseCapability be F.[[Capability]].
  7. Let remainingElementsCount be F.[[RemainingElements]].
  8. Set errors[index] to x.
  9. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
  10. If remainingElementsCount.[[Value]] is 0, then
    1. Let error be a newly created AggregateError object.
    2. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: ! CreateArrayFromList(errors) }).
    3. Return ? Call(promiseCapability.[[Reject]], undefined, « error »).
  11. Return undefined.

The "length" property of a Promise.any reject element function is 1𝔽.

27.2.4.4 Promise.prototype

The initial value of Promise.prototype is the Promise prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

27.2.4.5 Promise.race ( iterable )

The race function returns a new promise which is settled in the same way as the first passed promise to settle. It resolves all elements of the passed iterable to promises as it runs this algorithm.

  1. Let C be the this value.
  2. Let promiseCapability be ? NewPromiseCapability(C).
  3. Let promiseResolve be GetPromiseResolve(C).
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. Let iteratorRecord be GetIterator(iterable).
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. Let result be PerformPromiseRace(iteratorRecord, C, promiseCapability, promiseResolve).
  8. If result is an abrupt completion, then
    1. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. Return Completion(result).
Note 1

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.

Note 2

The race function expects its this value to be a constructor function that supports the parameter conventions of the Promise constructor. It also expects that its this value provides a resolve method.

27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseRace takes arguments iteratorRecord, constructor, resultCapability (a PromiseCapability Record), and promiseResolve. It performs the following steps when called:

  1. Assert: IsConstructor(constructor) is true.
  2. Assert: IsCallable(promiseResolve) is true.
  3. Repeat,
    1. Let next be IteratorStep(iteratorRecord).
    2. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
    3. ReturnIfAbrupt(next).
    4. If next is false, then
      1. Set iteratorRecord.[[Done]] to true.
      2. Return resultCapability.[[Promise]].
    5. Let nextValue be IteratorValue(next).
    6. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
    7. ReturnIfAbrupt(nextValue).
    8. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
    9. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).

27.2.4.6 Promise.reject ( r )

The reject function returns a new promise rejected with the passed argument.

  1. Let C be the this value.
  2. Let promiseCapability be ? NewPromiseCapability(C).
  3. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
  4. Return promiseCapability.[[Promise]].
Note

The reject function expects its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

27.2.4.7 Promise.resolve ( x )

The resolve function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this constructor.

  1. Let C be the this value.
  2. If Type(C) is not Object, throw a TypeError exception.
  3. Return ? PromiseResolve(C, x).
Note

The resolve function expects its this value to be a constructor function that supports the parameter conventions of the Promise constructor.

27.2.4.7.1 PromiseResolve ( C, x )

The abstract operation PromiseResolve takes arguments C (a constructor) and x (an ECMAScript language value). It returns a new promise resolved with x. It performs the following steps when called:

  1. Assert: Type(C) is Object.
  2. If IsPromise(x) is true, then
    1. Let xConstructor be ? Get(x, "constructor").
    2. If SameValue(xConstructor, C) is true, return x.
  3. Let promiseCapability be ? NewPromiseCapability(C).
  4. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
  5. Return promiseCapability.[[Promise]].

27.2.4.8 get Promise [ @@species ]

Promise[@@species] is an accessor property whose set accessor function is undefined. Its get accessor function performs the following steps:

  1. Return the this value.

The value of the "name" property of this function is "get [Symbol.species]".

Note

Promise prototype methods normally use their this value's constructor to create a derived object. However, a subclass constructor may over-ride that default behaviour by redefining its @@species property.

27.2.5 Properties of the Promise Prototype Object

The Promise prototype object:

  • is %Promise.prototype%.
  • has a [[Prototype]] internal slot whose value is %Object.prototype%.
  • is an ordinary object.
  • does not have a [[PromiseState]] internal slot or any of the other internal slots of Promise instances.

27.2.5.1 Promise.prototype.catch ( onRejected )

When the catch method is called with argument onRejected, the following steps are taken:

  1. Let promise be the this value.
  2. Return ? Invoke(promise, "then", « undefined, onRejected »).

27.2.5.2 Promise.prototype.constructor

The initial value of Promise.prototype.constructor is %Promise%.

27.2.5.3 Promise.prototype.finally ( onFinally )

When the finally method is called with argument onFinally, the following steps are taken:

  1. Let promise be the this value.
  2. If Type(promise) is not Object, throw a TypeError exception.
  3. Let C be ? SpeciesConstructor(promise, %Promise%).
  4. Assert: IsConstructor(C) is true.
  5. If IsCallable(onFinally) is false, then
    1. Let thenFinally be onFinally.
    2. Let catchFinally be onFinally.
  6. Else,
    1. Let stepsThenFinally be the algorithm steps defined in Then Finally Functions.
    2. Let lengthThenFinally be the number of non-optional parameters of the function definition in Then Finally Functions.
    3. Let thenFinally be ! CreateBuiltinFunction(stepsThenFinally, lengthThenFinally, "", « [[Constructor]], [[OnFinally]] »).
    4. Set thenFinally.[[Constructor]] to C.
    5. Set thenFinally.[[OnFinally]] to onFinally.
    6. Let stepsCatchFinally be the algorithm steps defined in Catch Finally Functions.
    7. Let lengthCatchFinally be the number of non-optional parameters of the function definition in Catch Finally Functions.
    8. Let catchFinally be ! CreateBuiltinFunction(stepsCatchFinally, lengthCatchFinally, "", « [[Constructor]], [[OnFinally]] »).
    9. Set catchFinally.[[Constructor]] to C.
    10. Set catchFinally.[[OnFinally]] to onFinally.
  7. Return ? Invoke(promise, "then", « thenFinally, catchFinally »).

27.2.5.3.1 Then Finally Functions

A Then Finally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a Promise-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.

When a Then Finally function is called with argument value, the following steps are taken:

  1. Let F be the active function object.
  2. Let onFinally be F.[[OnFinally]].
  3. Assert: IsCallable(onFinally) is true.
  4. Let result be ? Call(onFinally, undefined).
  5. Let C be F.[[Constructor]].
  6. Assert: IsConstructor(C) is true.
  7. Let promise be ? PromiseResolve(C, result).
  8. Let valueThunk be equivalent to a function that returns value.
  9. Return ? Invoke(promise, "then", « valueThunk »).

The "length" property of a Then Finally function is 1𝔽.

27.2.5.3.2 Catch Finally Functions

A Catch Finally function is an anonymous built-in function that has a [[Constructor]] and an [[OnFinally]] internal slot. The value of the [[Constructor]] internal slot is a Promise-like constructor function object, and the value of the [[OnFinally]] internal slot is a function object.

When a Catch Finally function is called with argument reason, the following steps are taken:

  1. Let F be the active function object.
  2. Let onFinally be F.[[OnFinally]].
  3. Assert: IsCallable(onFinally) is true.
  4. Let result be ? Call(onFinally, undefined).
  5. Let C be F.[[Constructor]].
  6. Assert: IsConstructor(C) is true.
  7. Let promise be ? PromiseResolve(C, result).
  8. Let thrower be equivalent to a function that throws reason.
  9. Return ? Invoke(promise, "then", « thrower »).

The "length" property of a Catch Finally function is 1𝔽.

27.2.5.4 Promise.prototype.then ( onFulfilled, onRejected )

When the then method is called with arguments onFulfilled and onRejected, the following steps are taken:

  1. Let promise be the this value.
  2. If IsPromise(promise) is false, throw a TypeError exception.
  3. Let C be ? SpeciesConstructor(promise, %Promise%).
  4. Let resultCapability be ? NewPromiseCapability(C).
  5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability).

27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] )

The abstract operation PerformPromiseThen takes arguments promise, onFulfilled, and onRejected and optional argument resultCapability (a PromiseCapability Record). It performs the “then” operation on promise using onFulfilled and onRejected as its settlement actions. If resultCapability is passed, the result is stored by updating resultCapability's promise. If it is not passed, then PerformPromiseThen is being called by a specification-internal operation where the result does not matter. It performs the following steps when called:

  1. Assert: IsPromise(promise) is true.
  2. If resultCapability is not present, then
    1. Set resultCapability to undefined.
  3. If IsCallable(onFulfilled) is false, then
    1. Let onFulfilledJobCallback be empty.
  4. Else,
    1. Let onFulfilledJobCallback be HostMakeJobCallback(onFulfilled).
  5. If IsCallable(onRejected) is false, then
    1. Let onRejectedJobCallback be empty.
  6. Else,
    1. Let onRejectedJobCallback be HostMakeJobCallback(onRejected).
  7. Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Fulfill, [[Handler]]: onFulfilledJobCallback }.
  8. Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Reject, [[Handler]]: onRejectedJobCallback }.
  9. If promise.[[PromiseState]] is pending, then
    1. Append fulfillReaction as the last element of the List that is promise.[[PromiseFulfillReactions]].
    2. Append rejectReaction as the last element of the List that is promise.[[PromiseRejectReactions]].
  10. Else if promise.[[PromiseState]] is fulfilled, then
    1. Let value be promise.[[PromiseResult]].
    2. Let fulfillJob be NewPromiseReactionJob(fulfillReaction, value).
    3. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]).
  11. Else,
    1. Assert: The value of promise.[[PromiseState]] is rejected.
    2. Let reason be promise.[[PromiseResult]].
    3. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "handle").
    4. Let rejectJob be NewPromiseReactionJob(rejectReaction, reason).
    5. Perform HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]).
  12. Set promise.[[PromiseIsHandled]] to true.
  13. If resultCapability is undefined, then
    1. Return undefined.
  14. Else,
    1. Return resultCapability.[[Promise]].

27.2.5.5 Promise.prototype [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "Promise".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.2.6 Properties of Promise Instances

Promise instances are ordinary objects that inherit properties from the Promise prototype object (the intrinsic, %Promise.prototype%). Promise instances are initially created with the internal slots described in Table 76.

Table 76: Internal Slots of Promise Instances
Internal Slot Description
[[PromiseState]] One of pending, fulfilled, or rejected. Governs how a promise will react to incoming calls to its then method.
[[PromiseResult]] The value with which the promise has been fulfilled or rejected, if any. Only meaningful if [[PromiseState]] is not pending.
[[PromiseFulfillReactions]] A List of PromiseReaction records to be processed when/if the promise transitions from the pending state to the fulfilled state.
[[PromiseRejectReactions]] A List of PromiseReaction records to be processed when/if the promise transitions from the 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.

27.3 GeneratorFunction Objects

GeneratorFunction objects are functions that are usually created by evaluating GeneratorDeclarations, GeneratorExpressions, and GeneratorMethods. They may also be created by calling the %GeneratorFunction% intrinsic.

Figure 5 (Informative): Generator Objects Relationships
A staggering variety of boxes and arrows.

27.3.1 The GeneratorFunction Constructor

The GeneratorFunction constructor:

  • is %GeneratorFunction%.
  • is a subclass of Function.
  • creates and initializes a new GeneratorFunction object when called as a function rather than as a constructor. Thus the function call GeneratorFunction (…) is equivalent to the object creation expression new GeneratorFunction (…) with the same arguments.
  • 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.

27.3.1.1 GeneratorFunction ( p1, p2, … , pn, body )

The last argument specifies the body (executable code) of a generator function; any preceding arguments specify formal parameters.

When the GeneratorFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “p” arguments, and where body might also not be provided), the following steps are taken:

  1. Let C be the active function object.
  2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
  3. Return ? CreateDynamicFunction(C, NewTarget, generator, args).
Note

See NOTE for 20.2.1.1.

27.3.2 Properties of the GeneratorFunction Constructor

The GeneratorFunction constructor:

  • is a standard built-in function object that inherits from the Function constructor.
  • has a [[Prototype]] internal slot whose value is %Function%.
  • has a "name" property whose value is "GeneratorFunction".
  • has the following properties:

27.3.2.1 GeneratorFunction.length

This is a data property with a value of 1. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.3.2.2 GeneratorFunction.prototype

The initial value of GeneratorFunction.prototype is the GeneratorFunction prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

27.3.3 Properties of the GeneratorFunction Prototype Object

The GeneratorFunction prototype object:

27.3.3.1 GeneratorFunction.prototype.constructor

The initial value of GeneratorFunction.prototype.constructor is %GeneratorFunction%.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.3.3.2 GeneratorFunction.prototype.prototype

The initial value of GeneratorFunction.prototype.prototype is the Generator prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.3.3.3 GeneratorFunction.prototype [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "GeneratorFunction".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.3.4 GeneratorFunction Instances

Every GeneratorFunction instance is an ECMAScript function object and has the internal slots listed in Table 33. The value of the [[IsClassConstructor]] internal slot for all such instances is false.

Each GeneratorFunction instance has the following own properties:

27.3.4.1 length

The specification for the "length" property of Function instances given in 20.2.4.1 also applies to GeneratorFunction instances.

27.3.4.2 name

The specification for the "name" property of Function instances given in 20.2.4.2 also applies to GeneratorFunction instances.

27.3.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]]: true, [[Enumerable]]: false, [[Configurable]]: false }.

Note

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.

27.4 AsyncGeneratorFunction Objects

AsyncGeneratorFunction objects are functions that are usually created by evaluating AsyncGeneratorDeclaration, AsyncGeneratorExpression, and AsyncGeneratorMethod syntactic productions. They may also be created by calling the %AsyncGeneratorFunction% intrinsic.

27.4.1 The AsyncGeneratorFunction Constructor

The AsyncGeneratorFunction constructor:

  • is %AsyncGeneratorFunction%.
  • is a subclass of Function.
  • creates and initializes a new AsyncGeneratorFunction object when called as a function rather than as a constructor. Thus the function call AsyncGeneratorFunction (...) is equivalent to the object creation expression new AsyncGeneratorFunction (...) with the same arguments.
  • 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 AsyncGeneratorFunction behaviour must include a super call to the AsyncGeneratorFunction constructor to create and initialize subclass instances with the internal slots necessary for built-in AsyncGeneratorFunction behaviour. All ECMAScript syntactic forms for defining async generator function objects create direct instances of AsyncGeneratorFunction. There is no syntactic means to create instances of AsyncGeneratorFunction subclasses.

27.4.1.1 AsyncGeneratorFunction ( p1, p2, … , pn, body )

The last argument specifies the body (executable code) of an async generator function; any preceding arguments specify formal parameters.

When the AsyncGeneratorFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no "p" arguments, and where body might also not be provided), the following steps are taken:

  1. Let C be the active function object.
  2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
  3. Return ? CreateDynamicFunction(C, NewTarget, asyncGenerator, args).
Note

See NOTE for 20.2.1.1.

27.4.2 Properties of the AsyncGeneratorFunction Constructor

The AsyncGeneratorFunction constructor:

  • is a standard built-in function object that inherits from the Function constructor.
  • has a [[Prototype]] internal slot whose value is %Function%.
  • has a "name" property whose value is "AsyncGeneratorFunction".
  • has the following properties:

27.4.2.1 AsyncGeneratorFunction.length

This is a data property with a value of 1. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.4.2.2 AsyncGeneratorFunction.prototype

The initial value of AsyncGeneratorFunction.prototype is the AsyncGeneratorFunction prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

27.4.3 Properties of the AsyncGeneratorFunction Prototype Object

The AsyncGeneratorFunction prototype object:

27.4.3.1 AsyncGeneratorFunction.prototype.constructor

The initial value of AsyncGeneratorFunction.prototype.constructor is %AsyncGeneratorFunction%.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.4.3.2 AsyncGeneratorFunction.prototype.prototype

The initial value of AsyncGeneratorFunction.prototype.prototype is the AsyncGenerator prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.4.3.3 AsyncGeneratorFunction.prototype [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "AsyncGeneratorFunction".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.4.4 AsyncGeneratorFunction Instances

Every AsyncGeneratorFunction instance is an ECMAScript function object and has the internal slots listed in Table 33. The value of the [[IsClassConstructor]] internal slot for all such instances is false.

Each AsyncGeneratorFunction instance has the following own properties:

27.4.4.1 length

The value of the "length" property is an integral Number 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]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.4.4.2 name

The specification for the "name" property of Function instances given in 20.2.4.2 also applies to AsyncGeneratorFunction instances.

27.4.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 function object is invoked using [[Call]].

This property has the attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.

Note

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.

27.5 Generator Objects

A Generator object is an instance of a generator function and conforms to both the Iterator and Iterable interfaces.

Generator instances directly inherit properties from the object that is the initial value of the "prototype" property of the Generator function that created the instance. Generator instances indirectly inherit properties from the Generator Prototype intrinsic, %GeneratorFunction.prototype.prototype%.

27.5.1 Properties of the Generator Prototype Object

The Generator prototype object:

  • is %GeneratorFunction.prototype.prototype%.
  • is an ordinary object.
  • is not a Generator instance and does not have a [[GeneratorState]] internal slot.
  • has a [[Prototype]] internal slot whose value is %IteratorPrototype%.
  • has properties that are indirectly inherited by all Generator instances.

27.5.1.1 Generator.prototype.constructor

The initial value of Generator.prototype.constructor is %GeneratorFunction.prototype%.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.5.1.2 Generator.prototype.next ( value )

The next method performs the following steps:

  1. Let g be the this value.
  2. Return ? GeneratorResume(g, value, empty).

27.5.1.3 Generator.prototype.return ( value )

The return method performs the following steps:

  1. Let g be the this value.
  2. Let C be Completion { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  3. Return ? GeneratorResumeAbrupt(g, C, empty).

27.5.1.4 Generator.prototype.throw ( exception )

The throw method performs the following steps:

  1. Let g be the this value.
  2. Let C be ThrowCompletion(exception).
  3. Return ? GeneratorResumeAbrupt(g, C, empty).

27.5.1.5 Generator.prototype [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "Generator".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.5.2 Properties of Generator Instances

Generator instances are initially created with the internal slots described in Table 77.

Table 77: Internal Slots of Generator Instances
Internal Slot Description
[[GeneratorState]] The current execution state of the generator. The possible values are: undefined, suspendedStart, suspendedYield, executing, and completed.
[[GeneratorContext]] The execution context that is used when executing the code of this generator.
[[GeneratorBrand]] A brand used to distinguish different kinds of generators. The [[GeneratorBrand]] of generators declared by ECMAScript source text is always empty.

27.5.3 Generator Abstract Operations

27.5.3.1 GeneratorStart ( generator, generatorBody )

The abstract operation GeneratorStart takes arguments generator and generatorBody (a Parse Node or an Abstract Closure with no parameters). It performs the following steps when called:

  1. Assert: The value of generator.[[GeneratorState]] is undefined.
  2. Let genContext be the running execution context.
  3. Set the Generator component of genContext to generator.
  4. Set the code evaluation state of genContext such that when evaluation is resumed for that execution context the following steps will be performed:
    1. If generatorBody is a Parse Node, then
      1. Let result be the result of evaluating generatorBody.
    2. Else,
      1. Assert: generatorBody is an Abstract Closure with no parameters.
      2. Let result be generatorBody().
    3. Assert: If we return here, the generator either threw an exception or performed either an implicit or explicit return.
    4. Remove genContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
    5. Set generator.[[GeneratorState]] to completed.
    6. Once a generator enters the completed state it never leaves it and its associated execution context is never resumed. Any execution state associated with generator can be discarded at this point.
    7. If result.[[Type]] is normal, let resultValue be undefined.
    8. Else if result.[[Type]] is return, let resultValue be result.[[Value]].
    9. Else,
      1. Assert: result.[[Type]] is throw.
      2. Return Completion(result).
    10. Return CreateIterResultObject(resultValue, true).
  5. Set generator.[[GeneratorContext]] to genContext.
  6. Set generator.[[GeneratorState]] to suspendedStart.
  7. Return NormalCompletion(undefined).

27.5.3.2 GeneratorValidate ( generator, generatorBrand )

The abstract operation GeneratorValidate takes arguments generator and generatorBrand. It performs the following steps when called:

  1. Perform ? RequireInternalSlot(generator, [[GeneratorState]]).
  2. Perform ? RequireInternalSlot(generator, [[GeneratorBrand]]).
  3. If generator.[[GeneratorBrand]] is not the same value as generatorBrand, throw a TypeError exception.
  4. Assert: generator also has a [[GeneratorContext]] internal slot.
  5. Let state be generator.[[GeneratorState]].
  6. If state is executing, throw a TypeError exception.
  7. Return state.

27.5.3.3 GeneratorResume ( generator, value, generatorBrand )

The abstract operation GeneratorResume takes arguments generator, value, and generatorBrand. It performs the following steps when called:

  1. Let state be ? GeneratorValidate(generator, generatorBrand).
  2. If state is completed, return CreateIterResultObject(undefined, true).
  3. Assert: state is either suspendedStart or suspendedYield.
  4. Let genContext be generator.[[GeneratorContext]].
  5. Let methodContext be the running execution context.
  6. Suspend methodContext.
  7. Set generator.[[GeneratorState]] to executing.
  8. Push genContext onto the execution context stack; genContext is now the running execution context.
  9. 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.
  10. Assert: When we return here, genContext has already been removed from the execution context stack and methodContext is the currently running execution context.
  11. Return Completion(result).

27.5.3.4 GeneratorResumeAbrupt ( generator, abruptCompletion, generatorBrand )

The abstract operation GeneratorResumeAbrupt takes arguments generator, abruptCompletion (a Completion Record whose [[Type]] is return or throw), and generatorBrand. It performs the following steps when called:

  1. Let state be ? GeneratorValidate(generator, generatorBrand).
  2. If state is suspendedStart, then
    1. Set generator.[[GeneratorState]] to completed.
    2. Once a generator enters the completed state it never leaves it and its associated execution context is never resumed. Any execution state associated with generator can be discarded at this point.
    3. Set state to completed.
  3. If state is completed, then
    1. If abruptCompletion.[[Type]] is return, then
      1. Return CreateIterResultObject(abruptCompletion.[[Value]], true).
    2. Return Completion(abruptCompletion).
  4. Assert: state is suspendedYield.
  5. Let genContext be generator.[[GeneratorContext]].
  6. Let methodContext be the running execution context.
  7. Suspend methodContext.
  8. Set generator.[[GeneratorState]] to executing.
  9. Push genContext onto the execution context stack; genContext is now the running execution context.
  10. 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.
  11. Assert: When we return here, genContext has already been removed from the execution context stack and methodContext is the currently running execution context.
  12. Return Completion(result).

27.5.3.5 GetGeneratorKind ( )

The abstract operation GetGeneratorKind takes no arguments. It performs the following steps when called:

  1. Let genContext be the running execution context.
  2. If genContext does not have a Generator component, return non-generator.
  3. Let generator be the Generator component of genContext.
  4. If generator has an [[AsyncGeneratorState]] internal slot, return async.
  5. Else, return sync.

27.5.3.6 GeneratorYield ( iterNextObj )

The abstract operation GeneratorYield takes argument iterNextObj. It performs the following steps when called:

  1. Assert: iterNextObj is an Object that implements the IteratorResult interface.
  2. Let genContext be the running execution context.
  3. Assert: genContext is the execution context of a generator.
  4. Let generator be the value of the Generator component of genContext.
  5. Assert: GetGeneratorKind() is sync.
  6. Set generator.[[GeneratorState]] to suspendedYield.
  7. Remove genContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
  8. Set the code evaluation state of genContext such that when evaluation is resumed with a Completion resumptionValue the following steps will be performed:
    1. Return resumptionValue.
    2. NOTE: This returns to the evaluation of the YieldExpression that originally called this abstract operation.
  9. Return NormalCompletion(iterNextObj).
  10. NOTE: This returns to the evaluation of the operation that had most previously resumed evaluation of genContext.

27.5.3.7 Yield ( value )

The abstract operation Yield takes argument value (an ECMAScript language value). It performs the following steps when called:

  1. Let generatorKind be ! GetGeneratorKind().
  2. If generatorKind is async, return ? AsyncGeneratorYield(value).
  3. Otherwise, return ? GeneratorYield(! CreateIterResultObject(value, false)).

27.5.3.8 CreateIteratorFromClosure ( closure, generatorBrand, generatorPrototype )

The abstract operation CreateIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), generatorBrand, and generatorPrototype (an Object). It performs the following steps when called:

  1. NOTE: closure can contain uses of the Yield shorthand to yield an IteratorResult object.
  2. Let internalSlotsList be « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] ».
  3. Let generator be ! OrdinaryObjectCreate(generatorPrototype, internalSlotsList).
  4. Set generator.[[GeneratorBrand]] to generatorBrand.
  5. Set generator.[[GeneratorState]] to undefined.
  6. Perform ! GeneratorStart(generator, closure).
  7. Return generator.

27.6 AsyncGenerator Objects

An AsyncGenerator object is an instance of an async generator function and conforms to both the AsyncIterator and AsyncIterable interfaces.

AsyncGenerator instances directly inherit properties from the object that is the initial value of the "prototype" property of the AsyncGenerator function that created the instance. AsyncGenerator instances indirectly inherit properties from the AsyncGenerator Prototype intrinsic, %AsyncGeneratorFunction.prototype.prototype%.

27.6.1 Properties of the AsyncGenerator Prototype Object

The AsyncGenerator prototype object:

  • is %AsyncGeneratorFunction.prototype.prototype%.
  • is an ordinary object.
  • is not an AsyncGenerator instance and does not have an [[AsyncGeneratorState]] internal slot.
  • has a [[Prototype]] internal slot whose value is %AsyncIteratorPrototype%.
  • has properties that are indirectly inherited by all AsyncGenerator instances.

27.6.1.1 AsyncGenerator.prototype.constructor

The initial value of AsyncGenerator.prototype.constructor is %AsyncGeneratorFunction.prototype%.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.6.1.2 AsyncGenerator.prototype.next ( value )

  1. Let generator be the this value.
  2. Let completion be NormalCompletion(value).
  3. Return ! AsyncGeneratorEnqueue(generator, completion, empty).

27.6.1.3 AsyncGenerator.prototype.return ( value )

  1. Let generator be the this value.
  2. Let completion be Completion { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  3. Return ! AsyncGeneratorEnqueue(generator, completion, empty).

27.6.1.4 AsyncGenerator.prototype.throw ( exception )

  1. Let generator be the this value.
  2. Let completion be ThrowCompletion(exception).
  3. Return ! AsyncGeneratorEnqueue(generator, completion, empty).

27.6.1.5 AsyncGenerator.prototype [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "AsyncGenerator".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.6.2 Properties of AsyncGenerator Instances

AsyncGenerator instances are initially created with the internal slots described below:

Table 78: Internal Slots of AsyncGenerator Instances
Internal Slot Description
[[AsyncGeneratorState]] The current execution state of the async generator. The possible values are: undefined, suspendedStart, suspendedYield, executing, awaiting-return, and completed.
[[AsyncGeneratorContext]] The execution context that is used when executing the code of this async generator.
[[AsyncGeneratorQueue]] A List of AsyncGeneratorRequest records which represent requests to resume the async generator.
[[GeneratorBrand]] A brand used to distinguish different kinds of async generators. The [[GeneratorBrand]] of async generators declared by ECMAScript source text is always empty.

27.6.3 AsyncGenerator Abstract Operations

27.6.3.1 AsyncGeneratorRequest Records

The AsyncGeneratorRequest is a Record value used to store information about how an async generator should be resumed and contains capabilities for fulfilling or rejecting the corresponding promise.

They have the following fields:

Table 79: AsyncGeneratorRequest Record Fields
Field Name Value Meaning
[[Completion]] A Completion record The completion which should be used to resume the async generator.
[[Capability]] A PromiseCapability Record The promise capabilities associated with this request.

27.6.3.2 AsyncGeneratorStart ( generator, generatorBody )

The abstract operation AsyncGeneratorStart takes arguments generator and generatorBody (a Parse Node or an Abstract Closure with no parameters). It performs the following steps when called:

  1. Assert: generator is an AsyncGenerator instance.
  2. Assert: generator.[[AsyncGeneratorState]] is undefined.
  3. Let genContext be the running execution context.
  4. Set the Generator component of genContext to generator.
  5. Set the code evaluation state of genContext such that when evaluation is resumed for that execution context the following steps will be performed:
    1. If generatorBody is a Parse Node, then
      1. Let result be the result of evaluating generatorBody.
    2. Else,
      1. Assert: generatorBody is an Abstract Closure with no parameters.
      2. Let result be generatorBody().
    3. Assert: If we return here, the async generator either threw an exception or performed either an implicit or explicit return.
    4. Remove genContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
    5. Set generator.[[AsyncGeneratorState]] to completed.
    6. If result is a normal completion, let resultValue be undefined.
    7. Else,
      1. Let resultValue be result.[[Value]].
      2. If result.[[Type]] is not return, then
        1. Return ! AsyncGeneratorReject(generator, resultValue).
    8. Return ! AsyncGeneratorResolve(generator, resultValue, true).
  6. Set generator.[[AsyncGeneratorContext]] to genContext.
  7. Set generator.[[AsyncGeneratorState]] to suspendedStart.
  8. Set generator.[[AsyncGeneratorQueue]] to a new empty List.
  9. Return undefined.

27.6.3.3 AsyncGeneratorValidate ( generator, generatorBrand )

The abstract operation AsyncGeneratorValidate takes arguments generator and generatorBrand. It performs the following steps when called:

  1. Perform ? RequireInternalSlot(generator, [[AsyncGeneratorContext]]).
  2. Perform ? RequireInternalSlot(generator, [[AsyncGeneratorState]]).
  3. Perform ? RequireInternalSlot(generator, [[AsyncGeneratorQueue]]).
  4. If generator.[[GeneratorBrand]] is not the same value as generatorBrand, throw a TypeError exception.

27.6.3.4 AsyncGeneratorResolve ( generator, value, done )

The abstract operation AsyncGeneratorResolve takes arguments generator, value, and done (a Boolean). It performs the following steps when called:

  1. Assert: generator is an AsyncGenerator instance.
  2. Let queue be generator.[[AsyncGeneratorQueue]].
  3. Assert: queue is not an empty List.
  4. Let next be the first element of queue.
  5. Remove the first element from queue.
  6. Let promiseCapability be next.[[Capability]].
  7. Let iteratorResult be ! CreateIterResultObject(value, done).
  8. Perform ! Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »).
  9. Perform ! AsyncGeneratorResumeNext(generator).
  10. Return undefined.

27.6.3.5 AsyncGeneratorReject ( generator, exception )

The abstract operation AsyncGeneratorReject takes arguments generator and exception. It performs the following steps when called:

  1. Assert: generator is an AsyncGenerator instance.
  2. Let queue be generator.[[AsyncGeneratorQueue]].
  3. Assert: queue is not an empty List.
  4. Let next be the first element of queue.
  5. Remove the first element from queue.
  6. Let promiseCapability be next.[[Capability]].
  7. Perform ! Call(promiseCapability.[[Reject]], undefined, « exception »).
  8. Perform ! AsyncGeneratorResumeNext(generator).
  9. Return undefined.

27.6.3.6 AsyncGeneratorResumeNext ( generator )

The abstract operation AsyncGeneratorResumeNext takes argument generator. It performs the following steps when called:

  1. Assert: generator is an AsyncGenerator instance.
  2. Let state be generator.[[AsyncGeneratorState]].
  3. Assert: state is not executing.
  4. If state is awaiting-return, return undefined.
  5. Let queue be generator.[[AsyncGeneratorQueue]].
  6. If queue is an empty List, return undefined.
  7. Let next be the value of the first element of queue.
  8. Assert: next is an AsyncGeneratorRequest record.
  9. Let completion be next.[[Completion]].
  10. If completion is an abrupt completion, then
    1. If state is suspendedStart, then
      1. Set generator.[[AsyncGeneratorState]] to completed.
      2. Set state to completed.
    2. If state is completed, then
      1. If completion.[[Type]] is return, then
        1. Set generator.[[AsyncGeneratorState]] to awaiting-return.
        2. Let promise be ? PromiseResolve(%Promise%, completion.[[Value]]).
        3. Let stepsFulfilled be the algorithm steps defined in AsyncGeneratorResumeNext Return Processor Fulfilled Functions.
        4. Let lengthFulfilled be the number of non-optional parameters of the function definition in AsyncGeneratorResumeNext Return Processor Fulfilled Functions.
        5. Let onFulfilled be ! CreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[Generator]] »).
        6. Set onFulfilled.[[Generator]] to generator.
        7. Let stepsRejected be the algorithm steps defined in AsyncGeneratorResumeNext Return Processor Rejected Functions.
        8. Let lengthRejected be the number of non-optional parameters of the function definition in AsyncGeneratorResumeNext Return Processor Rejected Functions.
        9. Let onRejected be ! CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[Generator]] »).
        10. Set onRejected.[[Generator]] to generator.
        11. Perform ! PerformPromiseThen(promise, onFulfilled, onRejected).
        12. Return undefined.
      2. Else,
        1. Assert: completion.[[Type]] is throw.
        2. Perform ! AsyncGeneratorReject(generator, completion.[[Value]]).
        3. Return undefined.
  11. Else if state is completed, return ! AsyncGeneratorResolve(generator, undefined, true).
  12. Assert: state is either suspendedStart or suspendedYield.
  13. Let genContext be generator.[[AsyncGeneratorContext]].
  14. Let callerContext be the running execution context.
  15. Suspend callerContext.
  16. Set generator.[[AsyncGeneratorState]] to executing.
  17. Push genContext onto the execution context stack; genContext is now the running execution context.
  18. 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.
  19. Assert: result is never an abrupt completion.
  20. Assert: When we return here, genContext has already been removed from the execution context stack and callerContext is the currently running execution context.
  21. Return undefined.

27.6.3.6.1 AsyncGeneratorResumeNext Return Processor Fulfilled Functions

An AsyncGeneratorResumeNext return processor fulfilled function is an anonymous built-in function that is used as part of the AsyncGeneratorResumeNext specification device to unwrap promises passed in to the AsyncGenerator.prototype.return ( value ) method. Each AsyncGeneratorResumeNext return processor fulfilled function has a [[Generator]] internal slot.

When an AsyncGeneratorResumeNext return processor fulfilled function is called with argument value, the following steps are taken:

  1. Let F be the active function object.
  2. Set F.[[Generator]].[[AsyncGeneratorState]] to completed.
  3. Return ! AsyncGeneratorResolve(F.[[Generator]], value, true).

The "length" property of an AsyncGeneratorResumeNext return processor fulfilled function is 1𝔽.

27.6.3.6.2 AsyncGeneratorResumeNext Return Processor Rejected Functions

An AsyncGeneratorResumeNext return processor rejected function is an anonymous built-in function that is used as part of the AsyncGeneratorResumeNext specification device to unwrap promises passed in to the AsyncGenerator.prototype.return ( value ) method. Each AsyncGeneratorResumeNext return processor rejected function has a [[Generator]] internal slot.

When an AsyncGeneratorResumeNext return processor rejected function is called with argument reason, the following steps are taken:

  1. Let F be the active function object.
  2. Set F.[[Generator]].[[AsyncGeneratorState]] to completed.
  3. Return ! AsyncGeneratorReject(F.[[Generator]], reason).

The "length" property of an AsyncGeneratorResumeNext return processor rejected function is 1𝔽.

27.6.3.7 AsyncGeneratorEnqueue ( generator, completion, generatorBrand )

The abstract operation AsyncGeneratorEnqueue takes arguments generator, completion (a Completion Record), and generatorBrand. It performs the following steps when called:

  1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  2. Let check be AsyncGeneratorValidate(generator, generatorBrand).
  3. If check is an abrupt completion, then
    1. Let badGeneratorError be a newly created TypeError object.
    2. Perform ! Call(promiseCapability.[[Reject]], undefined, « badGeneratorError »).
    3. Return promiseCapability.[[Promise]].
  4. Let queue be generator.[[AsyncGeneratorQueue]].
  5. Let request be AsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }.
  6. Append request to the end of queue.
  7. Let state be generator.[[AsyncGeneratorState]].
  8. If state is not executing, then
    1. Perform ! AsyncGeneratorResumeNext(generator).
  9. Return promiseCapability.[[Promise]].

27.6.3.8 AsyncGeneratorYield ( value )

The abstract operation AsyncGeneratorYield takes argument value. It performs the following steps when called:

  1. Let genContext be the running execution context.
  2. Assert: genContext is the execution context of a generator.
  3. Let generator be the value of the Generator component of genContext.
  4. Assert: GetGeneratorKind() is async.
  5. Set value to ? Await(value).
  6. Set generator.[[AsyncGeneratorState]] to suspendedYield.
  7. Remove genContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
  8. Set the code evaluation state of genContext such that when evaluation is resumed with a Completion resumptionValue the following steps will be performed:
    1. If resumptionValue.[[Type]] is not return, return Completion(resumptionValue).
    2. Let awaited be Await(resumptionValue.[[Value]]).
    3. If awaited.[[Type]] is throw, return Completion(awaited).
    4. Assert: awaited.[[Type]] is normal.
    5. Return Completion { [[Type]]: return, [[Value]]: awaited.[[Value]], [[Target]]: empty }.
    6. NOTE: When one of the above steps returns, it returns to the evaluation of the YieldExpression production that originally called this abstract operation.
  9. Return ! AsyncGeneratorResolve(generator, value, false).
  10. NOTE: This returns to the evaluation of the operation that had most previously resumed evaluation of genContext.

27.6.3.9 CreateAsyncIteratorFromClosure ( closure, generatorBrand, generatorPrototype )

The abstract operation CreateAsyncIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), generatorBrand, and generatorPrototype (an Object). It performs the following steps when called:

  1. NOTE: closure can contain uses of the Await shorthand and uses of the Yield shorthand to yield an IteratorResult object.
  2. Let internalSlotsList be « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] ».
  3. Let generator be ! OrdinaryObjectCreate(generatorPrototype, internalSlotsList).
  4. Set generator.[[GeneratorBrand]] to generatorBrand.
  5. Set generator.[[AsyncGeneratorState]] to undefined.
  6. Perform ! AsyncGeneratorStart(generator, closure).
  7. Return generator.

27.7 AsyncFunction Objects

AsyncFunction objects are functions that are usually created by evaluating AsyncFunctionDeclarations, AsyncFunctionExpressions, AsyncMethods, and AsyncArrowFunctions. They may also be created by calling the %AsyncFunction% intrinsic.

27.7.1 The AsyncFunction Constructor

The AsyncFunction constructor:

  • is %AsyncFunction%.
  • is a subclass of Function.
  • creates and initializes a new AsyncFunction object when called as a function rather than as a constructor. Thus the function call AsyncFunction(…) is equivalent to the object creation expression new AsyncFunction(…) with the same arguments.
  • 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. All ECMAScript syntactic forms for defining async function objects create direct instances of AsyncFunction. There is no syntactic means to create instances of AsyncFunction subclasses.

27.7.1.1 AsyncFunction ( p1, p2, … , pn, body )

The last argument specifies the body (executable code) of an async function. Any preceding arguments specify formal parameters.

When the AsyncFunction function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no p arguments, and where body might also not be provided), the following steps are taken:

  1. Let C be the active function object.
  2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]].
  3. Return CreateDynamicFunction(C, NewTarget, async, args).
Note
See NOTE for 20.2.1.1.

27.7.2 Properties of the AsyncFunction Constructor

The AsyncFunction constructor:

  • is a standard built-in function object that inherits from the Function constructor.
  • has a [[Prototype]] internal slot whose value is %Function%.
  • has a "name" property whose value is "AsyncFunction".
  • has the following properties:

27.7.2.1 AsyncFunction.length

This is a data property with a value of 1. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.7.2.2 AsyncFunction.prototype

The initial value of AsyncFunction.prototype is the AsyncFunction prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

27.7.3 Properties of the AsyncFunction Prototype Object

The AsyncFunction prototype object:

27.7.3.1 AsyncFunction.prototype.constructor

The initial value of AsyncFunction.prototype.constructor is %AsyncFunction%

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.7.3.2 AsyncFunction.prototype [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "AsyncFunction".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

27.7.4 AsyncFunction Instances

Every AsyncFunction instance is an ECMAScript function object and has the internal slots listed in Table 33. The value of the [[IsClassConstructor]] internal slot for all such instances is false. 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 constructible.

Each AsyncFunction instance has the following own properties:

27.7.4.1 length

The specification for the "length" property of Function instances given in 20.2.4.1 also applies to AsyncFunction instances.

27.7.4.2 name

The specification for the "name" property of Function instances given in 20.2.4.2 also applies to AsyncFunction instances.

27.7.5 Async Functions Abstract Operations

27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody )

The abstract operation AsyncFunctionStart takes arguments promiseCapability (a PromiseCapability Record) and asyncFunctionBody. It performs the following steps when called:

  1. Let runningContext be the running execution context.
  2. Let asyncContext be a copy of runningContext.
  3. NOTE: Copying the execution state is required for the step below to resume its execution. It is ill-defined to resume a currently executing context.
  4. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed:
    1. Let result be the result of evaluating asyncFunctionBody.
    2. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.
    3. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
    4. If result.[[Type]] is normal, then
      1. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
    5. Else if result.[[Type]] is return, then
      1. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
    6. Else,
      1. Assert: result.[[Type]] is throw.
      2. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
    7. Return.
  5. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  6. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  7. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  8. Assert: result is a normal completion with a value of undefined. The possible sources of completion values are Await or, if the async function doesn't await anything, step 4.g above.
  9. Return.