27 제어 추상화 객체

27.1 반복

27.1.1 공통 반복 인터페이스

interface는 associated values가 specific specification과 match하는 property keys의 set입니다. interface의 specification에 의해 described된 모든 properties를 제공하는 any object는 그 interface에 conform합니다. interface는 distinct object로 represented되지 않습니다. 어떤 interface에도 conform하는 separately implemented objects가 많이 있을 수 있습니다. individual object는 multiple interfaces에 conform할 수 있습니다.

27.1.1.1 Iterable Interface

iterable interfaceTable 79에 described된 properties를 포함합니다:

Table 79: Iterable Interface Required Properties
Property Value Requirements
%Symbol.iterator% iterator object를 반환하는 function 반환된 object는 iterator interface에 conform해야 합니다.

27.1.1.2 Iterator Interface

iterator interface를 implement하는 object는 Table 80의 property를 include해야 합니다. Such objects는 또한 Table 81의 properties를 implement할 수 있습니다.

Table 80: Iterator Interface Required Properties
Property Value Requirements
"next" IteratorResult object를 반환하는 function 반환된 object는 IteratorResult interface에 conform해야 합니다. iteratornext method에 대한 previous call이 "done" property가 trueIteratorResult object를 반환했다면, 그 object의 next method에 대한 모든 subsequent calls도 "done" property가 trueIteratorResult object를 반환해야 합니다. 그러나 이 requirement는 enforced되지 않습니다.
Note 1

arguments는 next function에 passed될 수 있지만, 그 interpretation과 validity는 target iterator에 dependent합니다. for-of statement와 iterators의 other common users는 어떤 arguments도 pass하지 않으므로, 그러한 방식으로 사용될 것으로 expect되는 iterator objects는 arguments 없이 called되는 것을 deal할 준비가 되어 있어야 합니다.

Table 81: Iterator Interface Optional Properties
Property Value Requirements
"return" IteratorResult object를 반환하는 function 반환된 object는 IteratorResult interface에 conform해야 합니다. 이 method를 invoking하면 caller가 iterator에 대해 더 이상 next method calls를 make할 intention이 없음을 iterator object에 notifies합니다. 반환된 IteratorResult object는 typically value가 true"done" property와 return method의 argument로 passed된 value를 가진 "value" property를 가집니다. 그러나 이 requirement는 enforced되지 않습니다.
"throw" IteratorResult object를 반환하는 function 반환된 object는 IteratorResult interface에 conform해야 합니다. 이 method를 invoking하면 caller가 error condition을 detected했음을 iterator object에 notifies합니다. argument는 error condition을 identify하는 데 사용될 수 있으며 typically exception object입니다. typical response는 argument로 passed된 value를 throw하는 것입니다. method가 throw하지 않으면, 반환된 IteratorResult object는 typically value가 true"done" property를 가집니다.
Note 2

Typically 이 methods의 callers는 invoking하기 전에 their existence를 check해야 합니다. for-of, yield*, 및 array destructuring을 포함한 certain ECMAScript language features는 existence check를 수행한 후 이 methods를 call합니다. iterable objects를 arguments로 accept하는 most ECMAScript library functions도 conditionally 이들을 call합니다.

27.1.1.3 Async Iterable Interface

async iterable interfaceTable 82에 described된 properties를 포함합니다:

Table 82: Async Iterable Interface Required Properties
Property Value Requirements
%Symbol.asyncIterator% async iterator object를 반환하는 function 반환된 object는 async iterator interface에 conform해야 합니다.

27.1.1.4 Async Iterator Interface

async iterator interface를 implement하는 object는 Table 83의 properties를 include해야 합니다. Such objects는 또한 Table 84의 properties를 implement할 수 있습니다.

Table 83: Async Iterator Interface Required Properties
Property Value Requirements
"next" IteratorResult object에 대한 promise를 반환하는 function

반환된 promise는 fulfilled될 때 IteratorResult interface에 conform하는 object로 fulfill해야 합니다. async iteratornext method에 대한 previous call이 "done" property가 trueIteratorResult object에 대한 promise를 반환했다면, 그 object의 next method에 대한 모든 subsequent calls도 "done" property가 trueIteratorResult object에 대한 promise를 반환해야 합니다. 그러나 이 requirement는 enforced되지 않습니다.

Additionally, fulfillment value로 serves하는 IteratorResult object는 value가 promise(또는 “thenable”)가 아닌 "value" property를 가져야 합니다. 그러나 이 requirement도 enforced되지 않습니다.

Note 1

arguments는 next function에 passed될 수 있지만, 그 interpretation과 validity는 target async iterator에 dependent합니다. for-await-of statement와 async iterators의 other common users는 어떤 arguments도 pass하지 않으므로, 그러한 방식으로 사용될 것으로 expect되는 async iterator objects는 arguments 없이 called되는 것을 deal할 준비가 되어 있어야 합니다.

Table 84: Async Iterator Interface Optional Properties
Property Value Requirements
"return" IteratorResult object에 대한 promise를 반환하는 function

반환된 promise는 fulfilled될 때 IteratorResult interface에 conform하는 object로 fulfill해야 합니다. 이 method를 invoking하면 caller가 async iterator에 대해 더 이상 next method calls를 make할 intention이 없음을 async iterator object에 notifies합니다. 반환된 promise는 typically value가 true"done" property와 return method의 argument로 passed된 value를 가진 "value" property를 가지는 IteratorResult object로 fulfill합니다. 그러나 이 requirement는 enforced되지 않습니다.

Additionally, fulfillment value로 serves하는 IteratorResult object는 value가 promise(또는 “thenable”)가 아닌 "value" property를 가져야 합니다. argument value가 typical manner로 used되면, 그것이 rejected promise인 경우 same reason으로 rejected된 promise가 returned되어야 합니다; fulfilled promise인 경우 그 fulfillment value가 returned promise의 IteratorResult object fulfillment value의 "value" property로 used되어야 합니다. 그러나 이러한 requirements도 enforced되지 않습니다.

"throw" IteratorResult object에 대한 promise를 반환하는 function

반환된 promise는 fulfilled될 때 IteratorResult interface에 conform하는 object로 fulfill해야 합니다. 이 method를 invoking하면 caller가 error condition을 detected했음을 async iterator object에 notifies합니다. argument는 error condition을 identify하는 데 사용될 수 있으며 typically exception object입니다. typical response는 argument로 passed된 value로 reject하는 rejected promise를 반환하는 것입니다.

반환된 promise가 fulfilled되면, IteratorResult object fulfillment value는 typically value가 true"done" property를 가집니다. Additionally, value가 promise(또는 “thenable”)가 아닌 "value" property를 가져야 하지만, 이 requirement는 enforced되지 않습니다.

Note 2

Typically 이 methods의 callers는 invoking하기 전에 their existence를 check해야 합니다. for-await-ofyield*를 포함한 certain ECMAScript language features는 existence check를 수행한 후 이 methods를 call합니다.

27.1.1.5 IteratorResult Interface

IteratorResult interfaceTable 85에 listed된 properties를 포함합니다:

Table 85: IteratorResult Interface Properties
Property Value Requirements
"done" Boolean 이는 iterator next method call의 result status입니다. iterator의 end에 reached했다면 "done"true입니다. end에 reached하지 않았다면 "done"false이고 value가 available합니다. "done" property(own 또는 inherited)가 exist하지 않으면, value false를 가지는 것으로 considered됩니다.
"value" ECMAScript language value done이 false이면, 이는 current iteration element value입니다. done이 true이면, 이는 iterator의 return value입니다(제공한 경우). iterator가 return value를 가지지 않으면, "value"undefined입니다. 그 경우 conforming object가 explicit "value" property를 inherit하지 않는다면 "value" property는 absent일 수 있습니다.

27.1.2 Iterator Helper 객체

Iterator Helper object는 some specific source iterator object의 lazy transformation을 represent하는 ordinary object입니다. Iterator Helper objects를 위한 named constructor는 없습니다. 대신, Iterator Helper objects는 Iterator instance objects의 certain methods를 calling하여 created됩니다.

27.1.2.1 The %IteratorHelperPrototype% Object

%IteratorHelperPrototype% object는:

27.1.2.1.1 %IteratorHelperPrototype%.next ( )

  1. GeneratorResume(this value, undefined, "Iterator Helper")를 반환한다.

27.1.2.1.2 %IteratorHelperPrototype%.return ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[UnderlyingIterators]])를 수행한다.
  3. Assert: obj[[GeneratorState]] internal slot을 가진다.
  4. obj.[[GeneratorState]]suspended-start이면, 다음을 수행한다.
    1. obj.[[GeneratorState]]completed로 설정한다.
    2. NOTE: generator가 completed state에 들어가면 결코 그 state를 떠나지 않으며 its associated execution context는 결코 resumed되지 않는다. obj와 associated된 any execution state는 이 point에서 discarded될 수 있다.
    3. IteratorCloseAll(obj.[[UnderlyingIterators]], NormalCompletion(unused))를 수행한다.
    4. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. completionReturnCompletion(undefined)으로 둔다.
  6. GeneratorResumeAbrupt(obj, completion, "Iterator Helper")를 반환한다.

27.1.2.1.3 %IteratorHelperPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Iterator Helper"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.1.3 Iterator 객체

27.1.3.1 Iterator 생성자

Iterator constructor는:

  • %Iterator%입니다.
  • global object"Iterator" property의 initial value입니다.
  • subclassable하도록 designed되었습니다. class definition의 extends clause의 value로 사용될 수 있습니다.

27.1.3.1.1 Iterator ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이거나 active function object이면, TypeError exception을 throw한다.
  2. OrdinaryCreateFromConstructor(NewTarget, "%Iterator.prototype%")를 반환한다.

27.1.3.2 Iterator 생성자의 속성

Iterator constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

27.1.3.2.1 Iterator.concat ( ...items )

  1. iterables를 new empty List로 둔다.
  2. items의 각 element item에 대해, 다음을 수행한다.
    1. item이 Object가 아니면, TypeError exception을 throw한다.
    2. method를 ? GetMethod(item, %Symbol.iterator%)로 둔다.
    3. methodundefined이면, TypeError exception을 throw한다.
    4. Record { [[OpenMethod]]: method, [[Iterable]]: item }를 iterables에 append한다.
  3. closureiterables를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. iterables의 각 Record iterable에 대해, 다음을 수행한다.
      1. iterator를 ? Call(iterable.[[OpenMethod]], iterable.[[Iterable]])로 둔다.
      2. iterator가 Object가 아니면, TypeError exception을 throw한다.
      3. iteratorRecord를 ? GetIteratorDirect(iterator)로 둔다.
      4. innerAlivetrue로 둔다.
      5. Repeat, while innerAlive is true,
        1. innerValue를 ? IteratorStepValue(iteratorRecord)로 둔다.
        2. innerValuedone이면, 다음을 수행한다.
          1. innerAlivefalse로 설정한다.
        3. Else,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion이면, 다음을 수행한다.
            1. IteratorClose(iteratorRecord, completion)를 반환한다.
    2. ReturnCompletion(undefined)을 반환한다.
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  5. gen.[[UnderlyingIterators]]를 new empty List로 설정한다.
  6. gen을 반환한다.

27.1.3.2.2 Iterator.from ( obj )

  1. iteratorRecord를 ? GetIteratorFlattenable(obj, iterate-string-primitives)로 둔다.
  2. hasInstance를 ? OrdinaryHasInstance(%Iterator%, iteratorRecord.[[Iterator]])로 둔다.
  3. hasInstancetrue이면, 다음을 수행한다.
    1. iteratorRecord.[[Iterator]]를 반환한다.
  4. wrapperOrdinaryObjectCreate(%WrapForValidIteratorPrototype%, « [[Iterated]] »)로 둔다.
  5. wrapper.[[Iterated]]iteratorRecord로 설정한다.
  6. wrapper를 반환한다.

27.1.3.2.2.1 The %WrapForValidIteratorPrototype% Object

%WrapForValidIteratorPrototype% object는:

27.1.3.2.2.1.1 %WrapForValidIteratorPrototype%.next ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[Iterated]])를 수행한다.
  3. iteratorRecordobj.[[Iterated]]로 둔다.
  4. Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])를 반환한다.

27.1.3.2.2.1.2 %WrapForValidIteratorPrototype%.return ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[Iterated]])를 수행한다.
  3. iteratorobj.[[Iterated]].[[Iterator]]로 둔다.
  4. Assert: iterator는 Object이다.
  5. returnMethod를 ? GetMethod(iterator, "return")로 둔다.
  6. returnMethodundefined이면, 다음을 수행한다.
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  7. Call(returnMethod, iterator)를 반환한다.

27.1.3.2.3 Iterator.prototype

Iterator.prototype의 initial value는 Iterator prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.1.3.2.4 Iterator.zip ( iterables [ , options ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. iterables가 Object가 아니면, TypeError exception을 throw한다.
  2. options를 ? GetOptionsObject(options)로 설정한다.
  3. mode를 ? Get(options, "mode")로 둔다.
  4. modeundefined이면, mode"shortest"로 설정한다.
  5. mode"shortest", "longest", 또는 "strict" 중 하나가 아니면, TypeError exception을 throw한다.
  6. paddingOptionundefined로 둔다.
  7. mode"longest"이면, 다음을 수행한다.
    1. paddingOption을 ? Get(options, "padding")으로 설정한다.
    2. paddingOptionundefined가 아니고 Object도 아니면, TypeError exception을 throw한다.
  8. iters를 new empty List로 둔다.
  9. padding을 new empty List로 둔다.
  10. inputIter를 ? GetIterator(iterables, sync)로 둔다.
  11. nextnot-started로 둔다.
  12. Repeat, while next is not done,
    1. nextCompletion(IteratorStepValue(inputIter))로 설정한다.
    2. IfAbruptCloseIterators(next, iters).
    3. nextdone이 아니면, 다음을 수행한다.
      1. iterCompletion(GetIteratorFlattenable(next, reject-primitives))로 둔다.
      2. needClosing을 « inputIter »와 iterslist-concatenation으로 둔다.
      3. IfAbruptCloseIterators(iter, needClosing).
      4. iteriters에 append한다.
  13. iterCountiters 안의 elements 수로 둔다.
  14. mode"longest"이면, 다음을 수행한다.
    1. paddingOptionundefined이면, 다음을 수행한다.
      1. Repeat iterCount times:
        1. undefinedpadding에 append한다.
    2. Else,
      1. paddingIterCompletion(GetIterator(paddingOption, sync))로 둔다.
      2. IfAbruptCloseIterators(paddingIter, iters).
      3. usingIteratortrue로 둔다.
      4. Repeat iterCount times:
        1. usingIteratortrue이면, 다음을 수행한다.
          1. nextCompletion(IteratorStepValue(paddingIter))로 설정한다.
          2. IfAbruptCloseIterators(next, iters).
          3. nextdone이면, 다음을 수행한다.
            1. usingIteratorfalse로 설정한다.
          4. Else,
            1. nextpadding에 append한다.
        2. usingIteratorfalse이면, undefinedpadding에 append한다.
      5. usingIteratortrue이면, 다음을 수행한다.
        1. completionCompletion(IteratorClose(paddingIter, NormalCompletion(unused)))로 둔다.
        2. IfAbruptCloseIterators(completion, iters).
  15. finishResults를 parameters (results)를 가지고 captures nothing하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. CreateArrayFromList(results)를 반환한다.
  16. IteratorZip(iters, mode, padding, finishResults)를 반환한다.

27.1.3.2.5 Iterator.zipKeyed ( iterables [ , options ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. iterables가 Object가 아니면, TypeError exception을 throw한다.
  2. options를 ? GetOptionsObject(options)로 설정한다.
  3. mode를 ? Get(options, "mode")로 둔다.
  4. modeundefined이면, mode"shortest"로 설정한다.
  5. mode"shortest", "longest", 또는 "strict" 중 하나가 아니면, TypeError exception을 throw한다.
  6. paddingOptionundefined로 둔다.
  7. mode"longest"이면, 다음을 수행한다.
    1. paddingOption을 ? Get(options, "padding")으로 설정한다.
    2. paddingOptionundefined가 아니고 Object도 아니면, TypeError exception을 throw한다.
  8. iters를 new empty List로 둔다.
  9. padding을 new empty List로 둔다.
  10. allKeys를 ? iterables.[[OwnPropertyKeys]]()로 둔다.
  11. keys를 new empty List로 둔다.
  12. allKeys의 각 element key에 대해, 다음을 수행한다.
    1. propertyDescCompletion(iterables.[[GetOwnProperty]](key))로 둔다.
    2. IfAbruptCloseIterators(propertyDesc, iters).
    3. propertyDescundefined가 아니고 propertyDesc.[[Enumerable]]true이면, 다음을 수행한다.
      1. valueCompletion(Get(iterables, key))로 둔다.
      2. IfAbruptCloseIterators(value, iters).
      3. valueundefined가 아니면, 다음을 수행한다.
        1. keykeys에 append한다.
        2. iterCompletion(GetIteratorFlattenable(value, reject-primitives))로 둔다.
        3. IfAbruptCloseIterators(iter, iters).
        4. iteriters에 append한다.
  13. iterCountiters 안의 elements 수로 둔다.
  14. mode"longest"이면, 다음을 수행한다.
    1. paddingOptionundefined이면, 다음을 수행한다.
      1. Repeat iterCount times:
        1. undefinedpadding에 append한다.
    2. Else,
      1. keys의 각 element key에 대해, 다음을 수행한다.
        1. valueCompletion(Get(paddingOption, key))로 둔다.
        2. IfAbruptCloseIterators(value, iters).
        3. valuepadding에 append한다.
  15. finishResults를 parameters (results)를 가지고 keysiterCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. objOrdinaryObjectCreate(null)로 둔다.
    2. 0 ≤ i < iterCount인 각 integer i에 대해, ascending order로, 다음을 수행한다.
      1. CreateDataPropertyOrThrow(obj, keys[i], results[i])를 수행한다.
    3. obj를 반환한다.
  16. IteratorZip(iters, mode, padding, finishResults)를 반환한다.

27.1.3.3 Iterator Prototype Object의 Properties

Iterator prototype object는:

Note

이 specification에서 iterator interface를 implement하도록 defined된 모든 objects는 또한 %Iterator.prototype%으로부터 inherit합니다. ECMAScript code도 %Iterator.prototype%으로부터 inherit하는 objects를 define할 수 있습니다. %Iterator.prototype%은 all iterator objects에 applicable한 additional methods가 added될 수 있는 place를 제공합니다.

다음 expression은 ECMAScript code가 %Iterator.prototype% object에 access할 수 있는 one way입니다:

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

27.1.3.3.1 Iterator.prototype.constructor

Iterator.prototype.constructor는 attributes { [[Enumerable]]: false, [[Configurable]]: true }를 가진 accessor property입니다. [[Get]][[Set]] attributes는 다음과 같이 defined됩니다:

27.1.3.3.1.1 get Iterator.prototype.constructor

[[Get]] attribute의 value는 arguments를 require하지 않는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. %Iterator%를 반환한다.

27.1.3.3.1.2 set Iterator.prototype.constructor

[[Set]] attribute의 value는 argument v를 takes하는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, "constructor", v)를 수행한다.
  2. undefined를 반환한다.
Note

most built-in prototypes의 "constructor" property와 unlike, web-compatibility reasons 때문에 이 property는 accessor여야 합니다.

27.1.3.3.2 Iterator.prototype.drop ( limit )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. numberLimitCompletion(ToNumber(limit))으로 둔다.
  5. IfAbruptCloseIterator(numberLimit, iterated).
  6. numberLimitNaN이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  7. intLimit을 ! ToIntegerOrInfinity(numberLimit)로 둔다.
  8. intLimit < 0이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  9. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  10. closureiteratedintLimit를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. remainingintLimit로 둔다.
    2. Repeat, while remaining > 0,
      1. remaining ≠ +∞이면, 다음을 수행한다.
        1. remainingremaining - 1로 설정한다.
      2. next를 ? IteratorStep(iterated)로 둔다.
      3. nextdone이면, ReturnCompletion(undefined)을 반환한다.
    3. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. completionCompletion(Yield(value))로 둔다.
      4. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  12. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  13. result를 반환한다.

27.1.3.3.3 Iterator.prototype.every ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, true를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 false이면, ? IteratorClose(iterated, NormalCompletion(false))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.4 Iterator.prototype.filter ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. closureiteratedpredicate를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. counter를 0으로 둔다.
    2. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. selectedCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(selected, iterated).
      5. ToBoolean(selected)가 true이면, 다음을 수행한다.
        1. completionCompletion(Yield(value))로 둔다.
        2. IfAbruptCloseIterator(completion, iterated).
      6. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.5 Iterator.prototype.find ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, undefined를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 true이면, ? IteratorClose(iterated, NormalCompletion(value))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.6 Iterator.prototype.flatMap ( mapper )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(mapper)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. closureiteratedmapper를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. counter를 0으로 둔다.
    2. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. innerIteratorCompletion(GetIteratorFlattenable(mapped, reject-primitives))로 둔다.
      6. IfAbruptCloseIterator(innerIterator, iterated).
      7. innerAlivetrue로 둔다.
      8. Repeat, while innerAlive is true,
        1. innerValueCompletion(IteratorStepValue(innerIterator))로 둔다.
        2. IfAbruptCloseIterator(innerValue, iterated).
        3. innerValuedone이면, 다음을 수행한다.
          1. innerAlivefalse로 설정한다.
        4. Else,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion이면, 다음을 수행한다.
            1. backupCompletionCompletion(IteratorClose(innerIterator, completion))로 둔다.
            2. IfAbruptCloseIterator(backupCompletion, iterated).
            3. IteratorClose(iterated, completion)를 반환한다.
      9. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.7 Iterator.prototype.forEach ( procedure )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(procedure)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, undefined를 반환한다.
    3. resultCompletion(Call(procedure, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. countercounter + 1로 설정한다.

27.1.3.3.8 Iterator.prototype.map ( mapper )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(mapper)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. closureiteratedmapper를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. counter를 0으로 둔다.
    2. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. completionCompletion(Yield(mapped))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
      7. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.9 Iterator.prototype.reduce ( reducer [ , initialValue ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(reducer)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. initialValue가 present하지 않으면, 다음을 수행한다.
    1. accumulator를 ? IteratorStepValue(iterated)로 둔다.
    2. accumulatordone이면, TypeError exception을 throw한다.
    3. counter를 1로 둔다.
  7. Else,
    1. accumulatorinitialValue로 둔다.
    2. counter를 0으로 둔다.
  8. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, accumulator를 반환한다.
    3. resultCompletion(Call(reducer, undefined, « accumulator, value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. accumulatorresult로 설정한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.10 Iterator.prototype.some ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, false를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 true이면, ? IteratorClose(iterated, NormalCompletion(true))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.11 Iterator.prototype.take ( limit )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. numberLimitCompletion(ToNumber(limit))으로 둔다.
  5. IfAbruptCloseIterator(numberLimit, iterated).
  6. numberLimitNaN이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  7. intLimit을 ! ToIntegerOrInfinity(numberLimit)로 둔다.
  8. intLimit < 0이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  9. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  10. closureiteratedintLimit를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. remainingintLimit로 둔다.
    2. Repeat,
      1. remaining = 0이면, 다음을 수행한다.
        1. IteratorClose(iterated, ReturnCompletion(undefined))를 반환한다.
      2. remaining ≠ +∞이면, 다음을 수행한다.
        1. remainingremaining - 1로 설정한다.
      3. value를 ? IteratorStepValue(iterated)로 둔다.
      4. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      5. completionCompletion(Yield(value))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  12. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  13. result를 반환한다.

27.1.3.3.12 Iterator.prototype.toArray ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iterated를 ? GetIteratorDirect(obj)로 둔다.
  4. items를 new empty List로 둔다.
  5. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, CreateArrayFromList(items)를 반환한다.
    3. valueitems에 append한다.

27.1.3.3.13 Iterator.prototype [ %Symbol.dispose% ] ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값으로 둔다.
  2. return을 ? GetMethod(obj, "return")으로 둔다.
  3. returnundefined가 아니면,
    1. Call(return, obj)를 수행한다.
  4. undefined를 반환한다.

이 메서드의 "name" 속성 값은 "[Symbol.dispose]"이다.

27.1.3.3.14 Iterator.prototype [ %Symbol.iterator% ] ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "[Symbol.iterator]"입니다.

27.1.3.3.15 Iterator.prototype [ %Symbol.toStringTag% ]

Iterator.prototype[%Symbol.toStringTag%]는 attributes { [[Enumerable]]: false, [[Configurable]]: true }를 가진 accessor property입니다. [[Get]][[Set]] attributes는 다음과 같이 defined됩니다:

27.1.3.3.15.1 get Iterator.prototype [ %Symbol.toStringTag% ]

[[Get]] attribute의 value는 arguments를 require하지 않는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. "Iterator"를 반환한다.

27.1.3.3.15.2 set Iterator.prototype [ %Symbol.toStringTag% ]

[[Set]] attribute의 value는 argument v를 takes하는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, %Symbol.toStringTag%, v)를 수행한다.
  2. undefined를 반환한다.
Note

most built-in prototypes의 %Symbol.toStringTag% property와 unlike, web-compatibility reasons 때문에 이 property는 accessor여야 합니다.

27.1.3.4 Iterators용 Abstract Operations

27.1.3.4.1 IteratorZip ( iters, mode, padding, finishResults )

The abstract operation IteratorZip takes arguments iters (a List of Iterator Records), mode ("shortest", "longest", or "strict"), padding (a List of ECMAScript language values), and finishResults (an Abstract Closure that takes a List of ECMAScript language values and returns an ECMAScript language value) and returns a Generator. It performs the following steps when called:

  1. iterCountiters 안의 elements 수로 둔다.
  2. openItersiters의 copy로 둔다.
  3. closureiters, iterCount, openIters, mode, padding, 및 finishResults를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. iterCount = 0이면, ReturnCompletion(undefined)을 반환한다.
    2. Repeat,
      1. results를 new empty List로 둔다.
      2. Assert: openIters는 empty가 아니다.
      3. 0 ≤ i < iterCount인 각 integer i에 대해, ascending order로, 다음을 수행한다.
        1. iteriters[i]로 둔다.
        2. iternull이면, 다음을 수행한다.
          1. Assert: mode"longest"이다.
          2. resultpadding[i]로 둔다.
        3. Else,
          1. resultCompletion(IteratorStepValue(iter))로 둔다.
          2. resultabrupt completion이면, 다음을 수행한다.
            1. iteropenIters에서 remove한다.
            2. IteratorCloseAll(openIters, result)를 반환한다.
          3. result를 ! result로 설정한다.
          4. resultdone이면, 다음을 수행한다.
            1. iteropenIters에서 remove한다.
            2. mode"shortest"이면, 다음을 수행한다.
              1. IteratorCloseAll(openIters, ReturnCompletion(undefined))를 반환한다.
            3. Else if mode is "strict", then
              1. i ≠ 0이면, 다음을 수행한다.
                1. IteratorCloseAll(openIters, ThrowCompletion(a newly created TypeError object))를 반환한다.
              2. 1 ≤ k < iterCount인 각 integer k에 대해, ascending order로, 다음을 수행한다.
                1. Assert: iters[k]는 null이 아니다.
                2. openCompletion(IteratorStep(iters[k]))으로 둔다.
                3. openabrupt completion이면, 다음을 수행한다.
                  1. iters[k]를 openIters에서 remove한다.
                  2. IteratorCloseAll(openIters, open)를 반환한다.
                4. open을 ! open으로 설정한다.
                5. opendone이면, 다음을 수행한다.
                  1. iters[k]를 openIters에서 remove한다.
                6. Else,
                  1. IteratorCloseAll(openIters, ThrowCompletion(a newly created TypeError object))를 반환한다.
              3. ReturnCompletion(undefined)을 반환한다.
            4. Else,
              1. Assert: mode"longest"이다.
              2. openIters가 empty이면, ReturnCompletion(undefined)을 반환한다.
              3. iters[i]를 null로 설정한다.
              4. resultpadding[i]로 설정한다.
        4. resultresults에 append한다.
      4. resultsfinishResults(results)로 설정한다.
      5. completionCompletion(Yield(results))로 둔다.
      6. IfAbruptCloseIterators(completion, openIters).
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  5. gen.[[UnderlyingIterators]]openIters로 설정한다.
  6. gen을 반환한다.

27.1.4 The %AsyncIteratorPrototype% Object

%AsyncIteratorPrototype% object는:

Note

이 specification에서 async iterator interface를 implement하도록 defined된 모든 objects는 또한 %AsyncIteratorPrototype%으로부터 inherit합니다. ECMAScript code도 %AsyncIteratorPrototype%으로부터 inherit하는 objects를 define할 수 있습니다. %AsyncIteratorPrototype% object는 all async iterator objects에 applicable한 additional methods가 added될 수 있는 place를 제공합니다.

27.1.4.1 %AsyncIteratorPrototype% [ %Symbol.asyncDispose% ] ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값으로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. returnCompletion(GetMethod(obj, "return"))으로 둔다.
  4. IfAbruptRejectPromise(return, promiseCapability).
  5. returnundefined이면,
    1. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
  6. 그렇지 않으면,
    1. resultCompletion(Call(return, obj, « »))으로 둔다.
    2. IfAbruptRejectPromise(result, promiseCapability).
    3. resultWrapperCompletion(PromiseResolve(%Promise%, result))로 둔다.
    4. IfAbruptRejectPromise(resultWrapper, promiseCapability).
    5. 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureunwrap을 둔다:
      1. undefined를 반환한다.
    6. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)로 둔다.
    7. PerformPromiseThen(resultWrapper, onFulfilled, undefined, promiseCapability)를 수행한다.
  7. promiseCapability.[[Promise]]를 반환한다.

이 메서드의 "name" 속성 값은 "[Symbol.asyncDispose]"이다.

27.1.4.2 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "[Symbol.asyncIterator]"입니다.

27.1.5 Async-from-Sync Iterator 객체

Async-from-Sync Iterator object는 specific synchronous iterator를 adapts하는 async iterator입니다. Async-from-Sync Iterator objects는 ECMAScript code에 직접 accessible하지 않습니다. Async-from-Sync Iterator objects를 위한 named constructor는 없습니다. 대신, Async-from-Sync Iterator objects는 needed에 따라 CreateAsyncFromSyncIterator abstract operation에 의해 created됩니다.

27.1.5.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )

The abstract operation CreateAsyncFromSyncIterator takes argument syncIteratorRecord (an Iterator Record) and returns an Iterator Record. synchronous Iterator Record로부터 async Iterator Record를 create하는 데 사용됩니다. It performs the following steps when called:

  1. asyncIteratorOrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »)로 둔다.
  2. asyncIterator.[[SyncIteratorRecord]]syncIteratorRecord로 설정한다.
  3. nextMethod를 ! Get(asyncIterator, "next")로 둔다.
  4. iteratorRecordIterator Record { [[Iterator]]: asyncIterator, [[NextMethod]]: nextMethod, [[Done]]: false }로 둔다.
  5. iteratorRecord를 반환한다.

27.1.5.2 The %AsyncFromSyncIteratorPrototype% Object

%AsyncFromSyncIteratorPrototype% object는:

27.1.5.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )

  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] internal slot을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. value가 present하면, 다음을 수행한다.
    1. resultCompletion(IteratorNext(syncIteratorRecord, value))로 둔다.
  6. Else,
    1. resultCompletion(IteratorNext(syncIteratorRecord))로 둔다.
  7. IfAbruptRejectPromise(result, promiseCapability).
  8. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.5.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )

  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] internal slot을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]]로 둔다.
  6. returnCompletion(GetMethod(syncIterator, "return"))으로 둔다.
  7. IfAbruptRejectPromise(return, promiseCapability).
  8. returnundefined이면, 다음을 수행한다.
    1. iteratorResultCreateIteratorResultObject(value, true)로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
    3. promiseCapability.[[Promise]]를 반환한다.
  9. value가 present하면, 다음을 수행한다.
    1. resultCompletion(Call(return, syncIterator, « value »))로 둔다.
  10. Else,
    1. resultCompletion(Call(return, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result가 Object가 아니면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, false)를 반환한다.

27.1.5.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )

Note
이 specification에서 value는 always provided되지만, %AsyncFromSyncIteratorPrototype%.return ( [ value ] )와의 consistency를 위해 optional로 left됩니다.
  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] internal slot을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]]로 둔다.
  6. throwCompletion(GetMethod(syncIterator, "throw"))으로 둔다.
  7. IfAbruptRejectPromise(throw, promiseCapability).
  8. throwundefined이면, 다음을 수행한다.
    1. NOTE: syncIteratorthrow method를 가지지 않으면, capability를 reject하기 전에 cleanup할 chance를 주기 위해 it을 close한다.
    2. closeCompletionNormalCompletion(empty)으로 둔다.
    3. resultCompletion(IteratorClose(syncIteratorRecord, closeCompletion))로 둔다.
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. NOTE: next step은 protocol violation이 있었다는 것을 indicate하기 위해 TypeError를 throw한다: syncIteratorthrow method를 가지지 않는다.
    6. NOTE: syncIterator를 closing하는 것이 throw하지 않으면 그 operation의 result는 ignored된다, rejected promise를 yields하더라도 마찬가지이다.
    7. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
    8. promiseCapability.[[Promise]]를 반환한다.
  9. value가 present하면, 다음을 수행한다.
    1. resultCompletion(Call(throw, syncIterator, « value »))로 둔다.
  10. Else,
    1. resultCompletion(Call(throw, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result가 Object가 아니면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.5.3 Async-from-Sync Iterator Instances의 Properties

Async-from-Sync Iterator instances는 %AsyncFromSyncIteratorPrototype% intrinsic object로부터 properties를 inherit하는 ordinary objects입니다. Async-from-Sync Iterator instances는 Table 86에 listed된 internal slots로 initially created됩니다.

Table 86: Internal Slots of Async-from-Sync Iterator Instances
Internal Slot Type Description
[[SyncIteratorRecord]] Iterator Record adapted되고 있는 original synchronous iterator를 represents합니다.

27.1.5.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability, syncIteratorRecord, closeOnRejection )

The abstract operation AsyncFromSyncIteratorContinuation takes arguments result (an Object), promiseCapability (a PromiseCapability Record for an intrinsic %Promise%), syncIteratorRecord (an Iterator Record), and closeOnRejection (a Boolean) and returns a Promise. It performs the following steps when called:

  1. NOTE: promiseCapability가 intrinsic %Promise%에서 derived되므로, 아래 IfAbruptRejectPromise의 use에 entailed되는 promiseCapability.[[Reject]]에 대한 calls는 throw하지 않음이 guaranteed된다.
  2. doneCompletion(IteratorComplete(result))로 둔다.
  3. IfAbruptRejectPromise(done, promiseCapability).
  4. valueCompletion(IteratorValue(result))로 둔다.
  5. IfAbruptRejectPromise(value, promiseCapability).
  6. valueWrapperCompletion(PromiseResolve(%Promise%, value))로 둔다.
  7. valueWrapperabrupt completion이고, donefalse이며, closeOnRejectiontrue이면, 다음을 수행한다.
    1. valueWrapperCompletion(IteratorClose(syncIteratorRecord, valueWrapper))로 설정한다.
  8. IfAbruptRejectPromise(valueWrapper, promiseCapability).
  9. unwrap을 parameters (v)를 가지고 done을 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. CreateIteratorResultObject(v, done)를 반환한다.
  10. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)로 둔다.
  11. NOTE: onFulfilledIteratorResult object"value" property를 processing할 때, 그 value가 promise이면 it을 wait하고 new “unwrapped” IteratorResult object로 result를 re-package하기 위해 used된다.
  12. donetrue이거나 closeOnRejectionfalse이면, 다음을 수행한다.
    1. onRejectedundefined로 둔다.
  13. Else,
    1. closeIterator를 parameters (error)를 가지고 syncIteratorRecord를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. IteratorClose(syncIteratorRecord, ThrowCompletion(error))를 반환한다.
    2. onRejectedCreateBuiltinFunction(closeIterator, 1, "", « »)로 둔다.
    3. NOTE: onRejected는 yields하는 IteratorResult object"value" property가 rejected promise일 때 Iterator를 close하는 데 used된다.
  14. PerformPromiseThen(valueWrapper, onFulfilled, onRejected, promiseCapability)를 수행한다.
  15. promiseCapability.[[Promise]]를 반환한다.

27.2 리소스 관리

27.2.1 공통 리소스 관리 인터페이스

27.2.1.1 Disposable 인터페이스

Disposable 인터페이스에는 Table 87에 설명된 속성이 포함된다:

Table 87: Disposable 인터페이스 필수 속성
속성 요구사항
%Symbol.dispose% 함수 객체

이 메서드를 호출하면 호출자가 이 객체를 계속 사용할 의도가 없음을 Disposable 객체에 알린다. 이 메서드는 파일 시스템 핸들, 스트림, 호스트 객체 등을 포함하되 이에 국한되지 않는 리소스의 명시적 정리를 수행하는 데 필요한 모든 로직을 수행해야 한다. 이 메서드에서 예외가 던져지면, 일반적으로 리소스를 명시적으로 해제할 수 없었음을 의미한다.

같은 객체에 대해 이 메서드를 두 번 이상 호출하는 경우, 이미 폐기된 리소스에 대해 정리 로직을 반복하지 않아야 하며, 첫 번째 호출에서 예외가 던져졌더라도 예외를 던지지 않아야 한다. 그러나 이 요구사항은 강제되지 않는다.

Disposable 객체를 using 또는 await using 선언과 함께 사용할 때, 리소스는 해당 선언을 바로 포함하는 Block 또는 Module이 평가된 후 자동으로 폐기된다.

27.2.1.2 AsyncDisposable 인터페이스

AsyncDisposable 인터페이스에는 Table 88에 설명된 속성이 포함된다:

Table 88: AsyncDisposable 인터페이스 필수 속성
속성 요구사항
%Symbol.asyncDispose% promise를 반환하는 함수 객체

이 메서드를 호출하면 호출자가 이 객체를 계속 사용할 의도가 없음을 AsyncDisposable 객체에 알린다. 이 메서드는 파일 시스템 핸들, 스트림, 호스트 객체 등을 포함하되 이에 국한되지 않는 리소스의 명시적 정리를 수행하는 데 필요한 모든 로직을 수행해야 한다. 이 메서드가 반환한 promise가 거부되면, 일반적으로 리소스를 명시적으로 해제할 수 없었음을 의미한다. AsyncDisposable 객체는 결과 Promise가 이행될 때까지 "disposed"된 것으로 간주되지 않는다.

같은 객체에 대해 이 메서드를 두 번 이상 호출하는 경우, 이미 폐기된 리소스에 대해 정리 로직을 반복하지 않아야 하며, 첫 번째 호출에서 예외가 던져졌거나 거부된 promise가 반환되었더라도 예외를 던지거나 거부된 promise를 반환하지 않아야 한다. 그러나 이 요구사항은 강제되지 않는다.

AsyncDisposable 객체를 await using 선언과 함께 사용할 때, 리소스는 해당 선언을 바로 포함하는 Block 또는 Module이 평가된 후 자동으로 폐기된다.

27.3 DisposableStack 객체

DisposableStack은 함께 폐기되어야 하는 하나 이상의 리소스를 담는 데 사용할 수 있는 객체이다.

모든 DisposableStack 객체는 서로 배타적인 두 상태 중 하나, 즉 disposed 또는 pending 상태에 있다. disposable stack d에 대해 d.dispose()d.move()가 모두 호출되지 않은 경우에만 d는 pending이다.

27.3.1 DisposableStack 생성자

DisposableStack 생성자는 다음과 같다:

  • %DisposableStack%이다.
  • 전역 객체의 "DisposableStack" 속성의 초기값이다.
  • 생성자로 호출될 때 새 DisposableStack을 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절에서 값으로 사용할 수 있다. 지정된 DisposableStack 동작을 상속하려는 하위 클래스 생성자는 DisposableStack.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 하위 클래스 인스턴스를 생성하고 초기화하기 위해 DisposableStack 생성자에 대한 super 호출을 포함해야 한다.

27.3.1.1 DisposableStack ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. disposableStack을 ? OrdinaryCreateFromConstructor(NewTarget, "%DisposableStack.prototype%", « [[DisposableState]], [[DisposableResourceStack]] »)로 둔다.
  3. disposableStack.[[DisposableState]]pending으로 설정한다.
  4. disposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  5. disposableStack을 반환한다.

27.3.2 DisposableStack 생성자의 속성

DisposableStack 생성자는 다음과 같다:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 다음 속성을 갖는다:

27.3.2.1 DisposableStack.prototype

DisposableStack.prototype의 초기값은 DisposableStack 프로토타입 객체이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 갖는다.

27.3.3 DisposableStack 프로토타입 객체의 속성

DisposableStack 프로토타입 객체는 다음과 같다:

  • %DisposableStack.prototype%이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 일반 객체이다.
  • [[DisposableState]] 내부 슬롯 또는 DisposableStack 인스턴스의 다른 내부 슬롯을 갖지 않는다.

27.3.3.1 DisposableStack.prototype.adopt ( value, onDispose )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDispose)가 false이면, TypeError 예외를 던진다.
  5. valueonDispose를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureclosure를 둔다:
    1. Call(onDispose, undefined, « value »)를 반환한다.
  6. funcCreateBuiltinFunction(closure, 0, "", « »)로 둔다.
  7. AddDisposableResource(disposableStack.[[DisposableResourceStack]], undefined, sync-dispose, func)를 수행한다.
  8. value를 반환한다.

27.3.3.2 DisposableStack.prototype.constructor

DisposableStack.prototype.constructor의 초기값은 %DisposableStack%이다.

27.3.3.3 DisposableStack.prototype.defer ( onDispose )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDispose)가 false이면, TypeError 예외를 던진다.
  5. AddDisposableResource(disposableStack.[[DisposableResourceStack]], undefined, sync-dispose, onDispose)를 수행한다.
  6. undefined를 반환한다.

27.3.3.4 DisposableStack.prototype.dispose ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, undefined를 반환한다.
  4. disposableStack.[[DisposableState]]disposed로 설정한다.
  5. DisposeResources(disposableStack.[[DisposableResourceStack]], NormalCompletion(undefined))를 반환한다.

27.3.3.5 get DisposableStack.prototype.disposed

DisposableStack.prototype.disposed는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, true를 반환한다.
  4. false를 반환한다.

27.3.3.6 DisposableStack.prototype.move ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. newDisposableStack을 ? OrdinaryCreateFromConstructor(%DisposableStack%, "%DisposableStack.prototype%", « [[DisposableState]], [[DisposableResourceStack]] »)로 둔다.
  5. newDisposableStack.[[DisposableState]]pending으로 설정한다.
  6. newDisposableStack.[[DisposableResourceStack]]disposableStack.[[DisposableResourceStack]]로 설정한다.
  7. disposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  8. disposableStack.[[DisposableState]]disposed로 설정한다.
  9. newDisposableStack을 반환한다.

27.3.3.7 DisposableStack.prototype.use ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. AddDisposableResource(disposableStack.[[DisposableResourceStack]], value, sync-dispose)를 수행한다.
  5. value를 반환한다.

27.3.3.8 DisposableStack.prototype [ %Symbol.dispose% ] ( )

%Symbol.dispose% 속성의 초기값은 27.3.3.4에 정의된 %DisposableStack.prototype.dispose%이다.

27.3.3.9 DisposableStack.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "DisposableStack"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 갖는다.

27.3.4 DisposableStack 인스턴스의 속성

DisposableStack 인스턴스는 DisposableStack 프로토타입 객체(내재 객체 %DisposableStack.prototype%)에서 속성을 상속하는 일반 객체이다. DisposableStack 인스턴스는 처음에 Table 89에 설명된 내부 슬롯과 함께 생성된다.

Table 89: DisposableStack 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[DisposableState]] pending 또는 disposed disposable stack이 자신의 %Symbol.dispose% 메서드에 대한 들어오는 호출에 어떻게 반응할지를 지배한다.
[[DisposableResourceStack]] DisposableResource 레코드List disposable stack이 폐기될 때 폐기될 리소스. 리소스는 초기화된 순서대로 추가되고, 역순으로 폐기된다.

27.4 AsyncDisposableStack 객체

AsyncDisposableStack은 함께 비동기적으로 폐기되어야 하는 하나 이상의 리소스를 담는 데 사용할 수 있는 객체이다.

모든 AsyncDisposableStack 객체는 서로 배타적인 두 상태 중 하나, 즉 disposed 또는 pending 상태에 있다. async-disposable stack d에 대해 d.disposeAsync()d.move()가 모두 호출되지 않은 경우에만 d는 pending이다.

27.4.1 AsyncDisposableStack 생성자

AsyncDisposableStack 생성자는 다음과 같다:

  • %AsyncDisposableStack%이다.
  • 전역 객체의 "AsyncDisposableStack" 속성의 초기값이다.
  • 생성자로 호출될 때 새 AsyncDisposableStack을 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절에서 값으로 사용할 수 있다. 지정된 AsyncDisposableStack 동작을 상속하려는 하위 클래스 생성자는 AsyncDisposableStack.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 하위 클래스 인스턴스를 생성하고 초기화하기 위해 AsyncDisposableStack 생성자에 대한 super 호출을 포함해야 한다.

27.4.1.1 AsyncDisposableStack ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. asyncDisposableStack을 ? OrdinaryCreateFromConstructor(NewTarget, "%AsyncDisposableStack.prototype%", « [[AsyncDisposableState]], [[DisposableResourceStack]] »)로 둔다.
  3. asyncDisposableStack.[[AsyncDisposableState]]pending으로 설정한다.
  4. asyncDisposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  5. asyncDisposableStack을 반환한다.

27.4.2 AsyncDisposableStack 생성자의 속성

AsyncDisposableStack 생성자는 다음과 같다:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 다음 속성을 갖는다:

27.4.2.1 AsyncDisposableStack.prototype

AsyncDisposableStack.prototype의 초기값은 AsyncDisposableStack 프로토타입 객체이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 갖는다.

27.4.3 AsyncDisposableStack 프로토타입 객체의 속성

AsyncDisposableStack 프로토타입 객체는 다음과 같다:

  • %AsyncDisposableStack.prototype%이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 일반 객체이다.
  • [[AsyncDisposableState]] 내부 슬롯 또는 AsyncDisposableStack 인스턴스의 다른 내부 슬롯을 갖지 않는다.

27.4.3.1 AsyncDisposableStack.prototype.adopt ( value, onDisposeAsync )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDisposeAsync)가 false이면, TypeError 예외를 던진다.
  5. valueonDisposeAsync를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureclosure를 둔다:
    1. Call(onDisposeAsync, undefined, « value »)를 반환한다.
  6. funcCreateBuiltinFunction(closure, 0, "", « »)로 둔다.
  7. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], undefined, async-dispose, func)를 수행한다.
  8. value를 반환한다.

27.4.3.2 AsyncDisposableStack.prototype.constructor

AsyncDisposableStack.prototype.constructor의 초기값은 %AsyncDisposableStack%이다.

27.4.3.3 AsyncDisposableStack.prototype.defer ( onDisposeAsync )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDisposeAsync)가 false이면, TypeError 예외를 던진다.
  5. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], undefined, async-dispose, onDisposeAsync)를 수행한다.
  6. undefined를 반환한다.

27.4.3.4 AsyncDisposableStack.prototype.disposeAsync ( )

이 async 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, undefined를 반환한다.
  4. asyncDisposableStack.[[AsyncDisposableState]]disposed로 설정한다.
  5. DisposeResources(asyncDisposableStack.[[DisposableResourceStack]], NormalCompletion(undefined))를 반환한다.

27.4.3.5 get AsyncDisposableStack.prototype.disposed

AsyncDisposableStack.prototype.disposed는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, true를 반환한다.
  4. false를 반환한다.

27.4.3.6 AsyncDisposableStack.prototype.move ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. newAsyncDisposableStack을 ? OrdinaryCreateFromConstructor(%AsyncDisposableStack%, "%AsyncDisposableStack.prototype%", « [[AsyncDisposableState]], [[DisposableResourceStack]] »)로 둔다.
  5. newAsyncDisposableStack.[[AsyncDisposableState]]pending으로 설정한다.
  6. newAsyncDisposableStack.[[DisposableResourceStack]]asyncDisposableStack.[[DisposableResourceStack]]로 설정한다.
  7. asyncDisposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  8. asyncDisposableStack.[[AsyncDisposableState]]disposed로 설정한다.
  9. newAsyncDisposableStack을 반환한다.

27.4.3.7 AsyncDisposableStack.prototype.use ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], value, async-dispose)를 수행한다.
  5. value를 반환한다.

27.4.3.8 AsyncDisposableStack.prototype [ %Symbol.asyncDispose% ] ( )

%Symbol.asyncDispose% 속성의 초기값은 27.4.3.4에 정의된 %AsyncDisposableStack.prototype.disposeAsync%이다.

27.4.3.9 AsyncDisposableStack.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "AsyncDisposableStack"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 갖는다.

27.4.4 AsyncDisposableStack 인스턴스의 속성

AsyncDisposableStack 인스턴스는 AsyncDisposableStack 프로토타입 객체(내재 객체 %AsyncDisposableStack.prototype%)에서 속성을 상속하는 일반 객체이다. AsyncDisposableStack 인스턴스는 처음에 Table 90에 설명된 내부 슬롯과 함께 생성된다.

Table 90: AsyncDisposableStack 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[AsyncDisposableState]] pending 또는 disposed disposable stack이 자신의 %Symbol.asyncDispose% 메서드에 대한 들어오는 호출에 어떻게 반응할지를 지배한다.
[[DisposableResourceStack]] DisposableResource 레코드List disposable stack이 폐기될 때 폐기될 리소스. 리소스는 초기화된 순서대로 추가되고, 역순으로 폐기된다.

27.5 Promise 객체

Promise는 deferred된(그리고 possibly asynchronous인) computation의 eventual results에 대한 placeholder로 사용되는 object입니다.

모든 Promise는 mutually exclusive한 세 states 중 하나입니다: fulfilled, rejected, 그리고 pending:

  • promise pp.then(f, r)가 function f를 call하는 Job을 immediately enqueue할 경우 fulfilled입니다.
  • promise pp.then(f, r)가 function r를 call하는 Job을 immediately enqueue할 경우 rejected입니다.
  • promise는 fulfilled도 rejected도 아니면 pending입니다.

promise는 pending이 아니면, 즉 fulfilled 또는 rejected이면 settled라고 합니다.

promise는 settled되었거나 다른 promise의 state와 match하도록 “locked in”된 경우 resolved입니다. resolved promise를 resolve 또는 reject하려는 시도는 effect가 없습니다. promise는 resolved가 아니면 unresolved입니다. unresolved promise는 항상 pending state입니다. resolved promise는 pending, fulfilled 또는 rejected일 수 있습니다.

27.5.1 Promise Abstract Operations

27.5.1.1 PromiseCapability Records

PromiseCapability Record는 Promise 또는 promise-like object를 그 promise를 resolve하거나 reject할 수 있는 functions와 함께 encapsulate하는 데 사용되는 Record value입니다. PromiseCapability Records는 NewPromiseCapability abstract operation에 의해 produced됩니다.

PromiseCapability Records는 Table 91에 listed된 fields를 가집니다.

Table 91: PromiseCapability Record Fields
Field Name Value Meaning
[[Promise]] Object promise로 usable한 object.
[[Resolve]] function object 주어진 promise를 resolve하는 데 사용되는 function.
[[Reject]] function object 주어진 promise를 reject하는 데 사용되는 function.

27.5.1.1.1 IfAbruptRejectPromise ( value, capability )

IfAbruptRejectPromise는 PromiseCapability Record를 사용하는 algorithm steps의 sequence에 대한 shorthand입니다. 다음 form의 algorithm step:

  1. IfAbruptRejectPromise(value, capability).

는 다음과 same thing을 의미합니다:

  1. Assert: valueCompletion Record이다.
  2. valueabrupt completion이면, 다음을 수행한다.
    1. Call(capability.[[Reject]], undefined, « value.[[Value]] »)를 수행한다.
    2. capability.[[Promise]]를 반환한다.
  3. value를 ! value로 설정한다.

27.5.1.2 PromiseReaction Records

PromiseReaction Record는 promise가 주어진 value로 resolved 또는 rejected될 때 어떻게 react해야 하는지에 대한 information을 store하는 데 사용되는 Record value입니다. PromiseReaction Records는 PerformPromiseThen abstract operation에 의해 created되며, NewPromiseReactionJob이 반환하는 Abstract Closure에 의해 used됩니다.

PromiseReaction Records는 Table 92에 listed된 fields를 가집니다.

Table 92: PromiseReaction Record Fields
Field Name Value Meaning
[[Capability]] PromiseCapability Record 또는 undefined 이 record가 reaction handler를 제공하는 promise의 capabilities.
[[Type]] fulfill 또는 reject [[Type]][[Handler]]empty일 때 settlement type에 specific한 behaviour를 allow하기 위해 사용됩니다.
[[Handler]] JobCallback Record 또는 empty incoming value에 applied되어야 하는 function이며, 그 return value가 derived promise에 무슨 일이 일어나는지를 govern합니다. [[Handler]]empty이면, [[Type]]의 value에 dependent한 function이 대신 사용됩니다.

27.5.1.3 CreateResolvingFunctions ( toResolve )

The abstract operation CreateResolvingFunctions takes argument toResolve (a Promise) and returns a Record with fields [[Resolve]] (a function object) and [[Reject]] (a function object). It performs the following steps when called:

  1. promiseOrEmptyRecord { [[Value]]: toResolve }로 둔다.
  2. resolveSteps를 parameters (resolution)를 가지고 promiseOrEmpty를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. promiseOrEmpty.[[Value]]empty이면, undefined를 반환한다.
    2. promisepromiseOrEmpty.[[Value]]로 둔다.
    3. promiseOrEmpty.[[Value]]empty로 설정한다.
    4. SameValue(resolution, promise)가 true이면, 다음을 수행한다.
      1. selfResolutionError를 newly created TypeError object로 둔다.
      2. RejectPromise(promise, selfResolutionError)를 수행한다.
      3. undefined를 반환한다.
    5. resolution이 Object가 아니면, 다음을 수행한다.
      1. FulfillPromise(promise, resolution)를 수행한다.
      2. undefined를 반환한다.
    6. thenCompletion(Get(resolution, "then")))로 둔다.
    7. thenabrupt completion이면, 다음을 수행한다.
      1. RejectPromise(promise, then.[[Value]])를 수행한다.
      2. undefined를 반환한다.
    8. thenActionthen.[[Value]]로 둔다.
    9. IsCallable(thenAction)가 false이면, 다음을 수행한다.
      1. FulfillPromise(promise, resolution)를 수행한다.
      2. undefined를 반환한다.
    10. thenJobCallbackHostMakeJobCallback(thenAction)로 둔다.
    11. jobNewPromiseResolveThenableJob(promise, resolution, thenJobCallback)으로 둔다.
    12. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])을 수행한다.
    13. undefined를 반환한다.
  3. resolveCreateBuiltinFunction(resolveSteps, 1, "", « »)로 둔다.
  4. rejectSteps를 parameters (reason)를 가지고 promiseOrEmpty를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. promiseOrEmpty.[[Value]]empty이면, undefined를 반환한다.
    2. promisepromiseOrEmpty.[[Value]]로 둔다.
    3. promiseOrEmpty.[[Value]]empty로 설정한다.
    4. RejectPromise(promise, reason)를 수행한다.
    5. undefined를 반환한다.
  5. rejectCreateBuiltinFunction(rejectSteps, 1, "", « »)로 둔다.
  6. Record { [[Resolve]]: resolve, [[Reject]]: reject }를 반환한다.

27.5.1.4 FulfillPromise ( promise, value )

The abstract operation FulfillPromise takes arguments promise (a Promise) and value (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Assert: promise.[[PromiseState]]pending이다.
  2. reactionspromise.[[PromiseFulfillReactions]]로 둔다.
  3. promise.[[PromiseResult]]value로 설정한다.
  4. promise.[[PromiseFulfillReactions]]undefined로 설정한다.
  5. promise.[[PromiseRejectReactions]]undefined로 설정한다.
  6. promise.[[PromiseState]]fulfilled로 설정한다.
  7. TriggerPromiseReactions(reactions, value)를 수행한다.
  8. unused를 반환한다.

27.5.1.5 NewPromiseCapability ( ctor )

The abstract operation NewPromiseCapability takes argument ctor (an ECMAScript language value) and returns either a normal completion containing a PromiseCapability Record or a throw completion. built-in Promise constructor의 방식으로 ctorconstructor로 사용하여 promise를 create하고 그 resolvereject functions를 extract하려고 attempts합니다. promise와 resolvereject functions는 new PromiseCapability Record를 initialize하는 데 사용됩니다. It performs the following steps when called:

  1. IsConstructor(ctor)가 false이면, TypeError exception을 throw한다.
  2. NOTE: ctor는 Promise constructor의 parameter conventions를 support하는 constructor function으로 assumed된다(27.5.3.1 참조).
  3. resolvingFuncsRecord { [[Resolve]]: undefined, [[Reject]]: undefined }로 둔다.
  4. executorClosure를 parameters (resolve, reject)를 가지고 resolvingFuncs를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. resolvingFuncs.[[Resolve]]undefined가 아니면, TypeError exception을 throw한다.
    2. resolvingFuncs.[[Reject]]undefined가 아니면, TypeError exception을 throw한다.
    3. resolvingFuncs.[[Resolve]]resolve로 설정한다.
    4. resolvingFuncs.[[Reject]]reject로 설정한다.
    5. NormalCompletion(undefined)을 반환한다.
  5. executorCreateBuiltinFunction(executorClosure, 2, "", « »)로 둔다.
  6. promise를 ? Construct(ctor, « executor »)로 둔다.
  7. IsCallable(resolvingFuncs.[[Resolve]])가 false이면, TypeError exception을 throw한다.
  8. IsCallable(resolvingFuncs.[[Reject]])가 false이면, TypeError exception을 throw한다.
  9. PromiseCapability Record { [[Promise]]: promise, [[Resolve]]: resolvingFuncs.[[Resolve]], [[Reject]]: resolvingFuncs.[[Reject]] }를 반환한다.
Note

이 abstract operation은 Promise subclassing을 support합니다. 이는 Promise constructor와 same way로 passed executor function argument를 call하는 any constructor에 대해 generic하기 때문입니다. Promise constructor의 static methods를 any subclass로 generalize하는 데 사용됩니다.

27.5.1.6 IsPromise ( arg )

The abstract operation IsPromise takes argument arg (an ECMAScript language value) and returns a Boolean. object에서 promise brand를 checks합니다. It performs the following steps when called:

  1. arg가 Object가 아니면, false를 반환한다.
  2. arg[[PromiseState]] internal slot을 가지지 않으면, false를 반환한다.
  3. true를 반환한다.

27.5.1.7 RejectPromise ( promise, reason )

The abstract operation RejectPromise takes arguments promise (a Promise) and reason (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Assert: promise.[[PromiseState]]pending이다.
  2. reactionspromise.[[PromiseRejectReactions]]로 둔다.
  3. promise.[[PromiseResult]]reason으로 설정한다.
  4. promise.[[PromiseFulfillReactions]]undefined로 설정한다.
  5. promise.[[PromiseRejectReactions]]undefined로 설정한다.
  6. promise.[[PromiseState]]rejected로 설정한다.
  7. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "reject")를 수행한다.
  8. TriggerPromiseReactions(reactions, reason)를 수행한다.
  9. unused를 반환한다.

27.5.1.8 TriggerPromiseReactions ( reactions, arg )

The abstract operation TriggerPromiseReactions takes arguments reactions (a List of PromiseReaction Records) and arg (an ECMAScript language value) and returns unused. reactions 안의 각 record에 대해 new Job을 enqueue합니다. Such Job 각각은 PromiseReaction Record[[Type]][[Handler]]를 process하며, [[Handler]]empty가 아니면 주어진 argument를 passing하여 it을 calls합니다. [[Handler]]empty이면, behaviour는 [[Type]]에 의해 determined됩니다. It performs the following steps when called:

  1. reactions의 각 element reaction에 대해, 다음을 수행한다.
    1. jobNewPromiseReactionJob(reaction, arg)로 둔다.
    2. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])을 수행한다.
  2. unused를 반환한다.

27.5.1.9 HostPromiseRejectionTracker ( promise, operation )

The host-defined abstract operation HostPromiseRejectionTracker takes arguments promise (a Promise) and operation ("reject" or "handle") and returns unused. host environments가 promise rejections를 track할 수 있게 합니다.

HostPromiseRejectionTracker의 default implementation은 unused를 반환하는 것입니다.

Note 1

HostPromiseRejectionTracker는 두 scenarios에서 called됩니다:

  • promise가 any handlers 없이 rejected될 때, operation argument가 "reject"로 set되어 called됩니다.
  • rejected promise에 handler가 first time added될 때, operation argument가 "handle"로 set되어 called됩니다.

HostPromiseRejectionTracker의 typical implementation은 unhandled rejections를 developers에게 notify하려고 시도할 수 있으며, 그러한 previous notifications가 later new handlers being attached에 의해 invalidated되면 also notify하도록 careful할 수 있습니다.

Note 2

operation"handle"이면, implementation은 garbage collection을 interfere하는 way로 promise에 대한 reference를 hold해서는 안 됩니다. operation"reject"이면, rejections는 rare하고 hot code paths에 있지 않을 것으로 expected되므로 implementation은 promise에 대한 reference를 hold할 수 있습니다.

27.5.2 Promise Jobs

27.5.2.1 NewPromiseReactionJob ( reaction, arg )

The abstract operation NewPromiseReactionJob takes arguments reaction (a PromiseReaction Record) and arg (an ECMAScript language value) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record or null). incoming value에 appropriate handler를 apply하고, handler의 return value를 사용하여 that handler와 associated된 derived promise를 resolve 또는 reject하는 new Job Abstract Closure를 반환합니다. It performs the following steps when called:

  1. jobreactionarg를 captures하며 called될 때 다음 steps를 수행하는, parameters가 없는 new Job Abstract Closure로 둔다:
    1. promiseCapabilityreaction.[[Capability]]로 둔다.
    2. typereaction.[[Type]]으로 둔다.
    3. handlerreaction.[[Handler]]로 둔다.
    4. handlerempty이면, 다음을 수행한다.
      1. typefulfill이면, 다음을 수행한다.
        1. handlerResultNormalCompletion(arg)로 둔다.
      2. Else,
        1. Assert: typereject이다.
        2. handlerResultThrowCompletion(arg)로 둔다.
    5. Else,
      1. handlerResultCompletion(HostCallJobCallback(handler, undefined, « arg »))로 둔다.
    6. promiseCapabilityundefined이면, 다음을 수행한다.
      1. Assert: handlerResultabrupt completion이 아니다.
      2. empty를 반환한다.
    7. Assert: promiseCapabilityPromiseCapability Record이다.
    8. handlerResultabrupt completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »)를 반환한다.
    9. Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »)를 반환한다.
  2. handlerRealmnull로 둔다.
  3. reaction.[[Handler]]empty가 아니면, 다음을 수행한다.
    1. getHandlerRealmResultCompletion(GetFunctionRealm(reaction.[[Handler]].[[Callback]]))으로 둔다.
    2. getHandlerRealmResultnormal completion이면, handlerRealmgetHandlerRealmResult.[[Value]]로 설정한다.
    3. Else, handlerRealm을 current Realm Record로 설정한다.
    4. NOTE: handler가 undefined가 아닌 한 handlerRealm은 never null이다. handler가 revoked Proxy이고 ECMAScript code가 실행되지 않을 때, handlerRealm은 error objects를 create하는 데 사용된다.
  4. Record { [[Job]]: job, [[Realm]]: handlerRealm }를 반환한다.

27.5.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )

The abstract operation NewPromiseResolveThenableJob takes arguments promiseToResolve (a Promise), thenable (an Object), and then (a JobCallback Record) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record). It performs the following steps when called:

  1. jobpromiseToResolve, thenable, 및 then을 captures하며 called될 때 다음 steps를 수행하는, parameters가 없는 new Job Abstract Closure로 둔다:
    1. resolvingFuncsCreateResolvingFunctions(promiseToResolve)로 둔다.
    2. thenCallResultCompletion(HostCallJobCallback(then, thenable, « resolvingFuncs.[[Resolve]], resolvingFuncs.[[Reject]] »))로 둔다.
    3. thenCallResultabrupt completion이면, 다음을 수행한다.
      1. Call(resolvingFuncs.[[Reject]], undefined, « thenCallResult.[[Value]] »)를 반환한다.
    4. thenCallResult를 반환한다.
  2. getThenRealmResultCompletion(GetFunctionRealm(then.[[Callback]]))으로 둔다.
  3. getThenRealmResultnormal completion이면, thenRealmgetThenRealmResult.[[Value]]로 둔다.
  4. Else, thenRealm을 current Realm Record로 둔다.
  5. NOTE: thenRealm은 never null이다. then.[[Callback]]이 revoked Proxy이고 code가 실행되지 않을 때, thenRealm은 error objects를 create하는 데 사용된다.
  6. Record { [[Job]]: job, [[Realm]]: thenRealm }를 반환한다.
Note

Job은 supplied thenable과 its then method를 사용하여 given promise를 resolve합니다. 이 process는 then method의 evaluation이 any surrounding code의 evaluation이 completed된 후 occur하도록 보장하기 위해 Job으로 일어나야 합니다.

27.5.3 Promise Constructor

Promise constructor는:

  • %Promise%입니다.
  • global object"Promise" property의 initial value입니다.
  • constructor로 called될 때 new Promise를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, 그런 방식으로 called되면 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 Promise 동작을 상속하려는 서브클래스 생성자는 PromisePromise.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 Promise 생성자에 대한 super 호출을 포함해야 한다.

27.5.3.1 Promise ( executor )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. IsCallable(executor)가 false이면, TypeError exception을 throw한다.
  3. promise를 ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »)로 둔다.
  4. promise.[[PromiseState]]pending으로 설정한다.
  5. promise.[[PromiseResult]]empty로 설정한다.
  6. promise.[[PromiseFulfillReactions]]를 new empty List로 설정한다.
  7. promise.[[PromiseRejectReactions]]를 new empty List로 설정한다.
  8. promise.[[PromiseIsHandled]]false로 설정한다.
  9. resolvingFuncsCreateResolvingFunctions(promise)로 둔다.
  10. completionCompletion(Call(executor, undefined, « resolvingFuncs.[[Resolve]], resolvingFuncs.[[Reject]] »))로 둔다.
  11. completionabrupt completion이면, 다음을 수행한다.
    1. Call(resolvingFuncs.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  12. promise를 반환한다.
Note

executor argument는 function object여야 합니다. 이는 이 Promise에 의해 represented되는 possibly deferred action의 initiating 및 reporting completion을 위해 called됩니다. executor는 두 arguments, resolvereject로 called됩니다. 이들은 executor function이 deferred computation의 eventual completion 또는 failure를 report하는 데 사용할 수 있는 functions입니다. executor function에서 returning하는 것은 deferred action이 completed되었음을 의미하지 않고, eventual deferred action 수행 request가 accepted되었음을 의미할 뿐입니다.

executor function에 passed되는 resolve function은 single argument를 accepts합니다. executor code는 eventually associated Promise를 resolve하기 원함을 indicate하기 위해 resolve function을 call할 수 있습니다. resolve function에 passed되는 argument는 deferred action의 eventual value를 represent하며, actual fulfillment value 또는 fulfilled될 경우 value를 provide할 another promise일 수 있습니다.

executor function에 passed되는 reject function은 single argument를 accepts합니다. executor code는 associated Promise가 rejected되며 결코 fulfilled되지 않음을 indicate하기 위해 reject function을 eventually call할 수 있습니다. reject function에 passed되는 argument는 promise의 rejection value로 used됩니다. Typically Error object입니다.

Promise constructorexecutor function에 passed하는 resolve 및 reject functions는 associated promise를 actually resolve하고 reject할 capability를 가집니다. Subclasses는 resolve와 reject에 대해 customized values를 pass하는 different constructor behaviour를 가질 수 있습니다.

27.5.4 Promise Constructor의 Properties

Promise constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

27.5.4.1 Promise.all ( iterable )

이 function은 passed promises의 fulfillment values array로 fulfilled되는 new promise를 반환하거나, rejects하는 first passed promise의 reason으로 rejects합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAll(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 require합니다.

27.5.4.1.1 GetPromiseResolve ( promiseCtor )

The abstract operation GetPromiseResolve takes argument promiseCtor (a constructor) and returns either a normal completion containing a function object or a throw completion. It performs the following steps when called:

  1. promiseResolve를 ? Get(promiseCtor, "resolve")로 둔다.
  2. IsCallable(promiseResolve)가 false이면, TypeError exception을 throw한다.
  3. promiseResolve를 반환한다.

27.5.4.1.2 PerformPromiseAll ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAll takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. values를 new empty List로 둔다.
  2. NOTE: remainingElementsCount는 0 대신 1에서 시작하여, passed callback이 input iterator가 exhausted되기 전에 misbehaving "then"에 의해 called되는 경우에도 resultCapability.[[Resolve]]가 only once called되도록 ensure한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinedvalues에 append한다.
    4. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    5. fulfilledSteps를 parameters (value)를 가지고 values, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]]true로 설정한다.
      4. thisIndexactiveFunc.[[Index]]로 둔다.
      5. values[thisIndex]를 value로 설정한다.
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      7. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      8. undefined를 반환한다.
    6. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    7. onFulfilled.[[AlreadyCalled]]false로 설정한다.
    8. onFulfilled.[[Index]]index로 설정한다.
    9. indexindex + 1로 설정한다.
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    11. Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »)를 수행한다.

27.5.4.2 Promise.allSettled ( iterable )

이 function은 original promises가 모두 settled될 때, 즉 fulfilled 또는 rejected 중 하나가 될 때만 promise state snapshots의 array로 fulfilled되는 promise를 반환합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAllSettled(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 require합니다.

27.5.4.2.1 PerformPromiseAllSettled ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. values를 new empty List로 둔다.
  2. NOTE: remainingElementsCount는 0 대신 1에서 시작하여, passed callbacks 중 하나가 input iterator가 exhausted되기 전에 misbehaving "then"에 의해 called되는 경우에도 resultCapability.[[Resolve]]가 only once called되도록 ensure한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinedvalues에 append한다.
    4. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    5. alreadyCalledRecord { [[Value]]: false }로 둔다.
    6. fulfilledSteps를 parameters (value)를 가지고 values, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]].[[Value]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]].[[Value]]true로 설정한다.
      4. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
      5. CreateDataPropertyOrThrow(obj, "status", "fulfilled")를 수행한다.
      6. CreateDataPropertyOrThrow(obj, "value", value)를 수행한다.
      7. thisIndexactiveFunc.[[Index]]로 둔다.
      8. values[thisIndex]를 obj로 설정한다.
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      10. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      11. undefined를 반환한다.
    7. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    8. onFulfilled.[[AlreadyCalled]]alreadyCalled로 설정한다.
    9. onFulfilled.[[Index]]index로 설정한다.
    10. rejectedSteps를 parameters (error)를 가지고 values, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]].[[Value]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]].[[Value]]true로 설정한다.
      4. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
      5. CreateDataPropertyOrThrow(obj, "status", "rejected")를 수행한다.
      6. CreateDataPropertyOrThrow(obj, "reason", error)를 수행한다.
      7. thisIndexactiveFunc.[[Index]]로 둔다.
      8. values[thisIndex]를 obj로 설정한다.
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      10. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      11. undefined를 반환한다.
    11. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    12. onRejected.[[AlreadyCalled]]alreadyCalled로 설정한다.
    13. onRejected.[[Index]]index로 설정한다.
    14. indexindex + 1로 설정한다.
    15. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    16. Invoke(nextPromise, "then", « onFulfilled, onRejected »)를 수행한다.

27.5.4.3 Promise.any ( iterable )

이 function은 fulfilled되는 first given promise에 의해 fulfilled되거나, given promises가 모두 rejected되면 rejection reasons를 holding하는 AggregateError로 rejected되는 promise를 반환합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAny(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 require합니다.

27.5.4.3.1 PerformPromiseAny ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAny takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. errors를 new empty List로 둔다.
  2. NOTE: remainingElementsCount는 0 대신 1에서 시작하여, passed callback이 input iterator가 exhausted되기 전에 misbehaving "then"에 의해 called되는 경우에도 resultCapability.[[Reject]]가 only once called되도록 ensure한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. aggregateError를 newly created AggregateError object로 둔다.
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })를 수행한다.
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinederrors에 append한다.
    4. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    5. rejectedSteps를 parameters (error)를 가지고 errors, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]]true로 설정한다.
      4. thisIndexactiveFunc.[[Index]]로 둔다.
      5. errors[thisIndex]를 error로 설정한다.
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      7. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. aggregateError를 newly created AggregateError object로 둔다.
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })를 수행한다.
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)를 반환한다.
      8. undefined를 반환한다.
    6. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    7. onRejected.[[AlreadyCalled]]false로 설정한다.
    8. onRejected.[[Index]]index로 설정한다.
    9. indexindex + 1로 설정한다.
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    11. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »)를 수행한다.

27.5.4.4 Promise.prototype

Promise.prototype의 initial value는 Promise prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.5.4.5 Promise.race ( iterable )

이 function은 settle되는 first passed promise와 same way로 settled되는 new promise를 반환합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseRace(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note 1

iterable argument가 no values를 yield하거나 iterable에 의해 yielded된 promises 중 none이 ever settle하지 않으면, 이 method가 반환하는 pending promise는 never settled됩니다.

Note 2

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다. 또한 its this value가 resolve method를 provide할 것을 expects합니다.

27.5.4.5.1 PerformPromiseRace ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseRace takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. resultCapability.[[Promise]]를 반환한다.
    3. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    4. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »)를 수행한다.

27.5.4.6 Promise.reject ( reason )

이 function은 passed argument로 rejected된 new promise를 반환합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. Call(promiseCapability.[[Reject]], undefined, « reason »)를 수행한다.
  4. promiseCapability.[[Promise]]를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다.

27.5.4.7 Promise.resolve ( resolution )

이 function은 passed argument로 resolved된 new promise를 반환하거나, argument가 this constructor에 의해 produced된 promise이면 argument 자체를 반환합니다.

  1. ctorthis value로 둔다.
  2. ctor가 Object가 아니면, TypeError exception을 throw한다.
  3. PromiseResolve(ctor, resolution)를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다.

27.5.4.7.1 PromiseResolve ( ctor, resolution )

The abstract operation PromiseResolve takes arguments ctor (an Object) and resolution (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. resolution으로 resolved된 new promise를 반환합니다. It performs the following steps when called:

  1. IsPromise(resolution)가 true이면, 다음을 수행한다.
    1. resolutionCtor를 ? Get(resolution, "constructor")로 둔다.
    2. SameValue(resolutionCtor, ctor)가 true이면, resolution을 반환한다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. Call(promiseCapability.[[Resolve]], undefined, « resolution »)를 수행한다.
  4. promiseCapability.[[Promise]]를 반환한다.

27.5.4.8 Promise.try ( callback, ...args )

이 function은 called될 때 다음 steps를 수행합니다:

  1. ctorthis value로 둔다.
  2. ctor가 Object가 아니면, TypeError exception을 throw한다.
  3. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  4. statusCompletion(Call(callback, undefined, args))로 둔다.
  5. statusabrupt completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « status.[[Value]] »)를 수행한다.
  6. Else,
    1. Call(promiseCapability.[[Resolve]], undefined, « status.[[Value]] »)를 수행한다.
  7. promiseCapability.[[Promise]]를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다.

27.5.4.9 Promise.withResolvers ( )

이 function은 세 properties를 가진 object를 반환합니다: new promise와 그에 associated된 resolvereject functions.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  4. CreateDataPropertyOrThrow(obj, "promise", promiseCapability.[[Promise]])를 수행한다.
  5. CreateDataPropertyOrThrow(obj, "resolve", promiseCapability.[[Resolve]])를 수행한다.
  6. CreateDataPropertyOrThrow(obj, "reject", promiseCapability.[[Reject]])를 수행한다.
  7. obj를 반환한다.

27.5.4.10 get Promise [ %Symbol.species% ]

Promise[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

Promise prototype methods는 normally derived object를 create하기 위해 their this value's constructor를 사용합니다. 그러나 subclass constructor는 its %Symbol.species% property를 redefining하여 that default behaviour를 over-ride할 수 있습니다.

27.5.5 Promise Prototype Object의 Properties

Promise prototype object는:

  • %Promise.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[PromiseState]] internal slot 또는 Promise instances의 other internal slots 중 any를 가지지 않습니다.

27.5.5.1 Promise.prototype.catch ( onRejected )

이 method는 called될 때 다음 steps를 수행합니다:

  1. promisethis value로 둔다.
  2. Invoke(promise, "then", « undefined, onRejected »)를 반환한다.

27.5.5.2 Promise.prototype.constructor

Promise.prototype.constructor의 initial value는 %Promise%입니다.

27.5.5.3 Promise.prototype.finally ( onFinally )

이 method는 called될 때 다음 steps를 수행합니다:

  1. promisethis value로 둔다.
  2. promise가 Object가 아니면, TypeError exception을 throw한다.
  3. ctor를 ? SpeciesConstructor(promise, %Promise%)로 둔다.
  4. Assert: IsConstructor(ctor)는 true이다.
  5. IsCallable(onFinally)가 false이면, 다음을 수행한다.
    1. thenFinallyonFinally로 둔다.
    2. catchFinallyonFinally로 둔다.
  6. Else,
    1. thenFinallyClosure를 parameters (value)를 가지고 onFinallyctor를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. result를 ? Call(onFinally, undefined)로 둔다.
      2. p를 ? PromiseResolve(ctor, result)로 둔다.
      3. returnValue를 parameters가 없고 value를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
        1. NormalCompletion(value)를 반환한다.
      4. valueThunkCreateBuiltinFunction(returnValue, 0, "", « »)로 둔다.
      5. Invoke(p, "then", « valueThunk »)를 반환한다.
    2. thenFinallyCreateBuiltinFunction(thenFinallyClosure, 1, "", « »)로 둔다.
    3. catchFinallyClosure를 parameters (reason)를 가지고 onFinallyctor를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. result를 ? Call(onFinally, undefined)로 둔다.
      2. p를 ? PromiseResolve(ctor, result)로 둔다.
      3. throwReason을 parameters가 없고 reason을 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
        1. Throw reason.
      4. throwerCreateBuiltinFunction(throwReason, 0, "", « »)로 둔다.
      5. Invoke(p, "then", « thrower »)를 반환한다.
    4. catchFinallyCreateBuiltinFunction(catchFinallyClosure, 1, "", « »)로 둔다.
  7. Invoke(promise, "then", « thenFinally, catchFinally »)를 반환한다.

27.5.5.4 Promise.prototype.then ( onFulfilled, onRejected )

이 method는 called될 때 다음 steps를 수행합니다:

  1. promisethis value로 둔다.
  2. IsPromise(promise)가 false이면, TypeError exception을 throw한다.
  3. ctor를 ? SpeciesConstructor(promise, %Promise%)로 둔다.
  4. resultCapability를 ? NewPromiseCapability(ctor)로 둔다.
  5. PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability)를 반환한다.

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

The abstract operation PerformPromiseThen takes arguments promise (a Promise), onFulfilled (an ECMAScript language value), and onRejected (an ECMAScript language value) and optional argument resultCapability (a PromiseCapability Record) and returns an Object or undefined. onFulfilledonRejected를 settlement actions로 사용하여 promise에 “then” operation을 수행합니다. resultCapability가 passed되면, result는 resultCapability의 promise를 updating하여 stored됩니다. passed되지 않으면, PerformPromiseThen은 result가 matter하지 않는 specification-internal operation에 의해 called되고 있는 것입니다. It performs the following steps when called:

  1. Assert: IsPromise(promise)는 true이다.
  2. resultCapability가 present하지 않으면, 다음을 수행한다.
    1. resultCapabilityundefined로 설정한다.
  3. IsCallable(onFulfilled)가 false이면, 다음을 수행한다.
    1. onFulfilledJobCallbackempty로 둔다.
  4. Else,
    1. onFulfilledJobCallbackHostMakeJobCallback(onFulfilled)로 둔다.
  5. IsCallable(onRejected)가 false이면, 다음을 수행한다.
    1. onRejectedJobCallbackempty로 둔다.
  6. Else,
    1. onRejectedJobCallbackHostMakeJobCallback(onRejected)로 둔다.
  7. fulfillReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: fulfill, [[Handler]]: onFulfilledJobCallback }로 둔다.
  8. rejectReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: reject, [[Handler]]: onRejectedJobCallback }로 둔다.
  9. promise.[[PromiseState]]pending이면, 다음을 수행한다.
    1. fulfillReactionpromise.[[PromiseFulfillReactions]]에 append한다.
    2. rejectReactionpromise.[[PromiseRejectReactions]]에 append한다.
  10. Else if promise.[[PromiseState]] is fulfilled, then
    1. valuepromise.[[PromiseResult]]로 둔다.
    2. fulfillJobNewPromiseReactionJob(fulfillReaction, value)로 둔다.
    3. HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]])을 수행한다.
  11. Else,
    1. Assert: promise.[[PromiseState]]rejected이다.
    2. reasonpromise.[[PromiseResult]]로 둔다.
    3. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "handle")를 수행한다.
    4. rejectJobNewPromiseReactionJob(rejectReaction, reason)로 둔다.
    5. HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]])을 수행한다.
  12. promise.[[PromiseIsHandled]]true로 설정한다.
  13. resultCapabilityundefined이면, undefined를 반환한다.
  14. resultCapability.[[Promise]]를 반환한다.

27.5.5.5 Promise.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Promise"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.5.6 Promise Instances의 Properties

Promise instances는 Promise prototype object(intrinsic, %Promise.prototype%)로부터 properties를 inherit하는 ordinary objects입니다. Promise instances는 Table 93에 described된 internal slots로 initially created됩니다.

Table 93: Internal Slots of Promise Instances
Internal Slot Type Description
[[PromiseState]] pending, fulfilled, 또는 rejected promise가 its then method에 대한 incoming calls에 어떻게 react할지를 governs합니다.
[[PromiseResult]] ECMAScript language value 또는 empty promise가 fulfilled 또는 rejected된 value, if any. [[PromiseState]]pending인 경우에만 empty입니다.
[[PromiseFulfillReactions]] PromiseReaction RecordsList promise가 pending state에서 fulfilled state로 transitions할 때/한다면 processed될 Records.
[[PromiseRejectReactions]] PromiseReaction RecordsList promise가 pending state에서 rejected state로 transitions할 때/한다면 processed될 Records.
[[PromiseIsHandled]] Boolean promise가 fulfillment 또는 rejection handler를 ever had했는지를 indicates합니다; unhandled rejection tracking에 used됩니다.

27.6 GeneratorFunction 객체

GeneratorFunctions는 보통 GeneratorDeclaration, GeneratorExpression, 및 GeneratorMethod를 평가하여 생성되는 functions입니다. 또한 %GeneratorFunction% intrinsic을 호출하여 생성될 수도 있습니다.

Figure 6 (Informative): Generator 객체 관계
다양한 boxes와 arrows.

27.6.1 GeneratorFunction Constructor

GeneratorFunction constructor는:

  • %GeneratorFunction%입니다.
  • Function의 subclass입니다.
  • constructor가 아니라 function으로 호출될 때 새 GeneratorFunction을 생성하고 초기화합니다. 따라서 function call GeneratorFunction (…)은 같은 arguments를 가진 object creation expression new GeneratorFunction (…)과 동등합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. 지정된 GeneratorFunction behaviour를 상속하려는 subclass constructors는 built-in GeneratorFunction behaviour에 필요한 internal slots를 가진 subclass instances를 생성하고 초기화하기 위해 GeneratorFunction constructor에 대한 super call을 포함해야 합니다. generator function objects를 정의하는 모든 ECMAScript syntactic forms는 GeneratorFunction의 direct instances를 생성합니다. GeneratorFunction subclasses의 instances를 생성하는 syntactic means는 없습니다.

27.6.1.1 GeneratorFunction ( ...paramArgs, bodyArg )

마지막 argument(있다면)는 generator function의 body(executable code)를 지정하고, preceding arguments는 formal parameters를 지정합니다.

이 function은 호출될 때 다음 steps를 수행합니다:

  1. activeFunc를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, generator, paramArgs, bodyArg)를 반환한다.
Note

20.2.1.1NOTE를 참조하십시오.

27.6.2 GeneratorFunction Constructor의 Properties

GeneratorFunction constructor는:

  • Function constructor에서 inherit하는 standard built-in function object입니다.
  • value가 %Function%[[Prototype]] internal slot을 가집니다.
  • value가 1𝔽"length" property를 가집니다.
  • value가 "GeneratorFunction""name" property를 가집니다.
  • 다음 properties를 가집니다:

27.6.2.1 GeneratorFunction.prototype

GeneratorFunction.prototype의 initial value는 GeneratorFunction prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.6.3 GeneratorFunction Prototype Object의 Properties

GeneratorFunction prototype object는:

27.6.3.1 GeneratorFunction.prototype.constructor

GeneratorFunction.prototype.constructor의 initial value는 %GeneratorFunction%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.6.3.2 GeneratorFunction.prototype.prototype

GeneratorFunction.prototype.prototype의 initial value는 %GeneratorPrototype%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.6.3.3 GeneratorFunction.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "GeneratorFunction"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.6.4 GeneratorFunction Instances

모든 GeneratorFunction instance는 ECMAScript function object이며 Table 26에 listed된 internal slots를 가집니다. 그러한 모든 instances의 [[IsClassConstructor]] internal slot의 value는 false입니다.

각 GeneratorFunction instance는 다음 own properties를 가집니다:

27.6.4.1 length

20.2.4.1에 given된 Function instances의 "length" property에 대한 specification은 GeneratorFunction instances에도 적용됩니다.

27.6.4.2 name

20.2.4.2에 given된 Function instances의 "name" property에 대한 specification은 GeneratorFunction instances에도 적용됩니다.

27.6.4.3 prototype

GeneratorFunction instance가 생성될 때마다 또 다른 ordinary object도 생성되며, 이는 generator function의 "prototype" property의 initial value입니다. prototype property의 value는 generator function object[[Call]]을 사용해 invoked될 때 newly created Generator의 [[Prototype]] internal slot을 initialize하는 데 사용됩니다.

이 property는 attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

Function instances와 달리, GeneratorFunction의 "prototype" property의 value인 object는 value가 GeneratorFunction instance인 "constructor" property를 가지지 않습니다.

27.7 AsyncGeneratorFunction 객체

AsyncGeneratorFunctions는 보통 AsyncGeneratorDeclaration, AsyncGeneratorExpression, 및 AsyncGeneratorMethod syntactic productions를 평가하여 생성되는 functions입니다. 또한 %AsyncGeneratorFunction% intrinsic을 호출하여 생성될 수도 있습니다.

27.7.1 AsyncGeneratorFunction Constructor

AsyncGeneratorFunction constructor는:

  • %AsyncGeneratorFunction%입니다.
  • Function의 subclass입니다.
  • constructor가 아니라 function으로 호출될 때 새 AsyncGeneratorFunction을 생성하고 초기화합니다. 따라서 function call AsyncGeneratorFunction (...)은 같은 arguments를 가진 object creation expression new AsyncGeneratorFunction (...)과 동등합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. 지정된 AsyncGeneratorFunction behaviour를 상속하려는 subclass constructors는 built-in AsyncGeneratorFunction behaviour에 필요한 internal slots를 가진 subclass instances를 생성하고 초기화하기 위해 AsyncGeneratorFunction constructor에 대한 super call을 포함해야 합니다. async generator function objects를 정의하는 모든 ECMAScript syntactic forms는 AsyncGeneratorFunction의 direct instances를 생성합니다. AsyncGeneratorFunction subclasses의 instances를 생성하는 syntactic means는 없습니다.

27.7.1.1 AsyncGeneratorFunction ( ...paramArgs, bodyArg )

마지막 argument(있다면)는 async generator function의 body(executable code)를 지정하고, preceding arguments는 formal parameters를 지정합니다.

이 function은 호출될 때 다음 steps를 수행합니다:

  1. activeFunc를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, async-generator, paramArgs, bodyArg)를 반환한다.
Note

20.2.1.1NOTE를 참조하십시오.

27.7.2 AsyncGeneratorFunction Constructor의 Properties

AsyncGeneratorFunction constructor는:

  • Function constructor에서 inherit하는 standard built-in function object입니다.
  • value가 %Function%[[Prototype]] internal slot을 가집니다.
  • value가 1𝔽"length" property를 가집니다.
  • value가 "AsyncGeneratorFunction""name" property를 가집니다.
  • 다음 properties를 가집니다:

27.7.2.1 AsyncGeneratorFunction.prototype

AsyncGeneratorFunction.prototype의 initial value는 AsyncGeneratorFunction prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.7.3 AsyncGeneratorFunction Prototype Object의 Properties

AsyncGeneratorFunction prototype object는:

27.7.3.1 AsyncGeneratorFunction.prototype.constructor

AsyncGeneratorFunction.prototype.constructor의 initial value는 %AsyncGeneratorFunction%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.7.3.2 AsyncGeneratorFunction.prototype.prototype

AsyncGeneratorFunction.prototype.prototype의 initial value는 %AsyncGeneratorPrototype%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.7.3.3 AsyncGeneratorFunction.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "AsyncGeneratorFunction"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.7.4 AsyncGeneratorFunction Instances

모든 AsyncGeneratorFunction instance는 ECMAScript function object이며 Table 26에 listed된 internal slots를 가집니다. 그러한 모든 instances의 [[IsClassConstructor]] internal slot의 value는 false입니다.

각 AsyncGeneratorFunction instance는 다음 own properties를 가집니다:

27.7.4.1 length

"length" property의 value는 AsyncGeneratorFunction이 expected하는 typical number of arguments를 나타내는 integral Number입니다. 그러나 language는 function이 다른 number of arguments로 invoked되는 것을 permits합니다. "length" property가 specified한 number가 아닌 number of arguments로 invoked될 때 AsyncGeneratorFunction의 behaviour는 function에 depends합니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.7.4.2 name

20.2.4.2에 given된 Function instances의 "name" property에 대한 specification은 AsyncGeneratorFunction instances에도 적용됩니다.

27.7.4.3 prototype

AsyncGeneratorFunction instance가 생성될 때마다 또 다른 ordinary object도 생성되며, 이는 async generator function의 "prototype" property의 initial value입니다. prototype property의 value는 generator function object[[Call]]을 사용해 invoked될 때 newly created AsyncGenerator의 [[Prototype]] internal slot을 initialize하는 데 사용됩니다.

이 property는 attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

function instances와 달리, AsyncGeneratorFunction의 "prototype" property의 value인 object는 value가 AsyncGeneratorFunction instance인 "constructor" property를 가지지 않습니다.

27.8 Generator 객체

Generator는 generator function을 호출하여 생성되며 iterator interfaceiterable interface 둘 다에 conforms합니다.

Generator instances는 instance를 생성한 generator function의 "prototype" property의 initial value에서 직접 properties를 inherit합니다. Generator instances는 %GeneratorPrototype%에서 간접적으로 properties를 inherit합니다.

27.8.1 %GeneratorPrototype% 객체

%GeneratorPrototype% object는:

  • %GeneratorFunction.prototype.prototype%입니다.
  • ordinary object입니다.
  • Generator instance가 아니며 [[GeneratorState]] internal slot을 가지지 않습니다.
  • value가 %Iterator.prototype%[[Prototype]] internal slot을 가집니다.
  • 모든 Generator instances가 indirectly inherit하는 properties를 가집니다.

27.8.1.1 %GeneratorPrototype%.constructor

%GeneratorPrototype%.constructor의 initial value는 %GeneratorFunction.prototype%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.8.1.2 %GeneratorPrototype%.next ( value )

  1. GeneratorResume(this value, value, empty)를 반환한다.

27.8.1.3 %GeneratorPrototype%.return ( value )

이 method는 호출될 때 다음 steps를 수행합니다:

  1. genthis value로 둔다.
  2. completionReturnCompletion(value)로 둔다.
  3. GeneratorResumeAbrupt(gen, completion, empty)를 반환한다.

27.8.1.4 %GeneratorPrototype%.throw ( exception )

이 method는 호출될 때 다음 steps를 수행합니다:

  1. genthis value로 둔다.
  2. completionThrowCompletion(exception)으로 둔다.
  3. GeneratorResumeAbrupt(gen, completion, empty)를 반환한다.

27.8.1.5 %GeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Generator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.8.2 Generator Instances의 Properties

Generator instances는 Table 94에 described된 internal slots로 initially created됩니다.

Table 94: Generator Instances의 Internal Slots
Internal Slot Type Description
[[GeneratorState]] suspended-start, suspended-yield, executing, 또는 completed generator의 current execution state.
[[GeneratorContext]] execution context 이 generator의 code를 executing할 때 사용되는 execution context.
[[GeneratorBrand]] String 또는 empty different kinds of generators를 distinguish하기 위해 사용되는 brand. ECMAScript source text로 declared된 generators의 [[GeneratorBrand]]는 항상 empty입니다.

27.8.3 Generator Abstract Operations

27.8.3.1 GeneratorStart ( gen, genBody )

The abstract operation GeneratorStart takes arguments gen (a Generator) and genBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[GeneratorState]]suspended-start이다.
  2. genContextrunning execution context로 둔다.
  3. genContext의 Generator component를 gen으로 설정한다.
  4. closure를 parameters가 없고 genBody를 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. acGenContextrunning execution context로 둔다.
    2. acGenacGenContext의 Generator component로 둔다.
    3. genBodyParse Node이면, 다음을 수행한다.
      1. resultCompletion(Evaluation of genBody)로 둔다.
    4. Else,
      1. Assert: genBody는 parameters가 없는 Abstract Closure이다.
      2. resultCompletion(genBody())로 둔다.
    5. Assert: 여기로 return한다면, generator는 exception을 throw했거나 implicit 또는 explicit return 중 하나를 수행했다.
    6. execution context stack에서 acGenContext를 remove하고, execution context stack의 top에 있는 execution contextrunning execution context로 restore한다.
    7. acGen.[[GeneratorState]]completed로 설정한다.
    8. NOTE: generator가 completed state에 들어가면 결코 이를 떠나지 않으며, its associated execution context는 결코 resumed되지 않는다. acGen과 associated된 any execution state는 이 시점에서 discarded될 수 있다.
    9. resultnormal completion이면, 다음을 수행한다.
      1. resultValueundefined로 둔다.
    10. Else if resultreturn completion이면, 다음을 수행한다.
      1. resultValueresult.[[Value]]로 둔다.
    11. Else,
      1. Assert: resultthrow completion이다.
      2. result를 반환한다.
    12. NormalCompletion(CreateIteratorResultObject(resultValue, true))를 반환한다.
  5. genContext의 code evaluation state를, 그 execution context에 대해 evaluation이 resumed될 때 closure가 no arguments로 called되도록 설정한다.
  6. gen.[[GeneratorContext]]genContext로 설정한다.
  7. unused를 반환한다.

27.8.3.2 GeneratorValidate ( gen, genBrand )

The abstract operation GeneratorValidate takes arguments gen (an ECMAScript language value) and genBrand (a String or empty) and returns either a normal completion containing one of suspended-start, suspended-yield, or completed, or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(gen, [[GeneratorState]])를 수행한다.
  2. RequireInternalSlot(gen, [[GeneratorBrand]])를 수행한다.
  3. gen.[[GeneratorBrand]]genBrand가 아니면, TypeError exception을 throw한다.
  4. Assert: gen[[GeneratorContext]] internal slot을 가진다.
  5. stategen.[[GeneratorState]]로 둔다.
  6. stateexecuting이면, TypeError exception을 throw한다.
  7. state를 반환한다.

27.8.3.3 GeneratorResume ( gen, value, genBrand )

The abstract operation GeneratorResume takes arguments gen (an ECMAScript language value), value (an ECMAScript language value or empty), and genBrand (a String or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. state를 ? GeneratorValidate(gen, genBrand)로 둔다.
  2. statecompleted이면, CreateIteratorResultObject(undefined, true)를 반환한다.
  3. Assert: statesuspended-start 또는 suspended-yield 중 하나이다.
  4. genContextgen.[[GeneratorContext]]로 둔다.
  5. gen.[[GeneratorState]]executing으로 설정한다.
  6. RunSuspendedContext(genContext, NormalCompletion(value))를 반환한다.

27.8.3.4 GeneratorResumeAbrupt ( gen, abruptCompletion, genBrand )

The abstract operation GeneratorResumeAbrupt takes arguments gen (an ECMAScript language value), abruptCompletion (a return completion or a throw completion), and genBrand (a String or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. state를 ? GeneratorValidate(gen, genBrand)로 둔다.
  2. statesuspended-start이면, 다음을 수행한다.
    1. gen.[[GeneratorState]]completed로 설정한다.
    2. NOTE: generator가 completed state에 들어가면 결코 이를 떠나지 않으며, its associated execution context는 결코 resumed되지 않는다. gen과 associated된 any execution state는 이 시점에서 discarded될 수 있다.
    3. statecompleted로 설정한다.
  3. statecompleted이면, 다음을 수행한다.
    1. abruptCompletionreturn completion이면, 다음을 수행한다.
      1. CreateIteratorResultObject(abruptCompletion.[[Value]], true)를 반환한다.
    2. abruptCompletion을 반환한다.
  4. Assert: statesuspended-yield이다.
  5. genContextgen.[[GeneratorContext]]로 둔다.
  6. gen.[[GeneratorState]]executing으로 설정한다.
  7. RunSuspendedContext(genContext, abruptCompletion)를 반환한다.

27.8.3.5 GetGeneratorKind ( )

The abstract operation GetGeneratorKind takes no arguments and returns non-generator, sync, or async. It performs the following steps when called:

  1. genContextrunning execution context로 둔다.
  2. genContext가 Generator component를 가지지 않으면, non-generator를 반환한다.
  3. gengenContext의 Generator component로 둔다.
  4. gen[[AsyncGeneratorState]] internal slot을 가지면, async를 반환한다.
  5. sync를 반환한다.

27.8.3.6 GeneratorYield ( iteratorResult )

The abstract operation GeneratorYield takes argument iteratorResult (an Object that conforms to the IteratorResult interface) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genContext를 실행 중인 실행 컨텍스트라 하자.
  2. Assert: genContext는 제너레이터의 실행 컨텍스트이다.
  3. gengenContext의 Generator 컴포넌트 값이라 하자.
  4. Assert: GetGeneratorKind()는 sync이다.
  5. gen.[[GeneratorState]]suspended-yield로 설정한다.
  6. RunCallerContext(iteratorResult)를 반환한다.

27.8.3.7 Yield ( arg )

The abstract operation Yield takes argument arg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genKindGetGeneratorKind()로 둔다.
  2. genKindasync이면, ? AsyncGeneratorYield(? Await(arg))를 반환한다.
  3. GeneratorYield(CreateIteratorResultObject(arg, false))를 반환한다.

27.8.3.8 CreateIteratorFromClosure ( closure, genBrand, genProto [ , extraSlots ] )

The abstract operation CreateIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), genBrand (a String or empty), and genProto (an Object) and optional argument extraSlots (a List of names of internal slots) and returns a Generator. It performs the following steps when called:

  1. NOTE: closureIteratorResult object를 yield하기 위해 Yield operation의 uses를 contain할 수 있다.
  2. extraSlots가 present하지 않으면, extraSlots를 new empty List로 설정한다.
  3. internalSlotsListextraSlots와 « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »의 list-concatenation으로 둔다.
  4. genOrdinaryObjectCreate(genProto, internalSlotsList)로 둔다.
  5. gen.[[GeneratorBrand]]genBrand로 설정한다.
  6. gen.[[GeneratorState]]suspended-start로 설정한다.
  7. callerContextrunning execution context로 둔다.
  8. calleeContext를 new execution context로 둔다.
  9. calleeContext의 Function을 null로 설정한다.
  10. calleeContextRealm을 current Realm Record로 설정한다.
  11. calleeContext의 ScriptOrModule을 callerContext의 ScriptOrModule로 설정한다.
  12. callerContext가 already suspended가 아니면, callerContext를 suspend한다.
  13. calleeContextexecution context stack에 Push한다; calleeContext는 이제 running execution context이다.
  14. GeneratorStart(gen, closure)를 수행한다.
  15. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
  16. gen을 반환한다.

27.9 AsyncGenerator 객체

AsyncGenerator는 async generator function을 호출하여 생성되며 async iterator interfaceasync iterable interface 둘 다에 conforms합니다.

AsyncGenerator instances는 instance를 생성한 async generator function의 "prototype" property의 initial value에서 직접 properties를 inherit합니다. AsyncGenerator instances는 %AsyncGeneratorPrototype%에서 간접적으로 properties를 inherit합니다.

27.9.1 %AsyncGeneratorPrototype% 객체

%AsyncGeneratorPrototype% object는:

  • %AsyncGeneratorFunction.prototype.prototype%입니다.
  • ordinary object입니다.
  • AsyncGenerator instance가 아니며 [[AsyncGeneratorState]] internal slot을 가지지 않습니다.
  • value가 %AsyncIteratorPrototype%[[Prototype]] internal slot을 가집니다.
  • 모든 AsyncGenerator instances가 indirectly inherit하는 properties를 가집니다.

27.9.1.1 %AsyncGeneratorPrototype%.constructor

%AsyncGeneratorPrototype%.constructor의 initial value는 %AsyncGeneratorFunction.prototype%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.9.1.2 %AsyncGeneratorPrototype%.next ( value )

  1. genthis value로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategen.[[AsyncGeneratorState]]로 둔다.
  6. statecompleted이면, 다음을 수행한다.
    1. iteratorResultCreateIteratorResultObject(undefined, true)로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
    3. promiseCapability.[[Promise]]를 반환한다.
  7. completionNormalCompletion(value)로 둔다.
  8. AsyncGeneratorEnqueue(gen, completion, promiseCapability)를 수행한다.
  9. statesuspended-start 또는 suspended-yield 중 하나이면, 다음을 수행한다.
    1. AsyncGeneratorResume(gen, completion)을 수행한다.
  10. Else,
    1. Assert: stateexecuting 또는 draining-queue 중 하나이다.
  11. promiseCapability.[[Promise]]를 반환한다.

27.9.1.3 %AsyncGeneratorPrototype%.return ( value )

  1. genthis value로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. completionReturnCompletion(value)로 둔다.
  6. AsyncGeneratorEnqueue(gen, completion, promiseCapability)를 수행한다.
  7. stategen.[[AsyncGeneratorState]]로 둔다.
  8. statesuspended-start 또는 completed 중 하나이면, 다음을 수행한다.
    1. gen.[[AsyncGeneratorState]]draining-queue로 설정한다.
    2. AsyncGeneratorAwaitReturn(gen)을 수행한다.
  9. Else if statesuspended-yield이면, 다음을 수행한다.
    1. AsyncGeneratorResume(gen, completion)을 수행한다.
  10. Else,
    1. Assert: stateexecuting 또는 draining-queue 중 하나이다.
  11. promiseCapability.[[Promise]]를 반환한다.

27.9.1.4 %AsyncGeneratorPrototype%.throw ( exception )

  1. genthis value로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategen.[[AsyncGeneratorState]]로 둔다.
  6. statesuspended-start이면, 다음을 수행한다.
    1. gen.[[AsyncGeneratorState]]completed로 설정한다.
    2. statecompleted로 설정한다.
  7. statecompleted이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « exception »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  8. completionThrowCompletion(exception)으로 둔다.
  9. AsyncGeneratorEnqueue(gen, completion, promiseCapability)를 수행한다.
  10. statesuspended-yield이면, 다음을 수행한다.
    1. AsyncGeneratorResume(gen, completion)을 수행한다.
  11. Else,
    1. Assert: stateexecuting 또는 draining-queue 중 하나이다.
  12. promiseCapability.[[Promise]]를 반환한다.

27.9.1.5 %AsyncGeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "AsyncGenerator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.9.2 AsyncGenerator Instances의 Properties

AsyncGenerator instances는 아래에 described된 internal slots로 initially created됩니다:

Table 95: AsyncGenerator Instances의 Internal Slots
Internal Slot Type Description
[[AsyncGeneratorState]] suspended-start, suspended-yield, executing, draining-queue, 또는 completed async generator의 current execution state.
[[AsyncGeneratorContext]] execution context 이 async generator의 code를 executing할 때 사용되는 execution context.
[[AsyncGeneratorQueue]] AsyncGeneratorRequest RecordsList async generator를 resume하기 위한 requests를 represent하는 Records. state transitions 동안을 제외하고, [[AsyncGeneratorState]]executing 또는 draining-queue 중 하나인 경우에만 non-empty입니다.
[[GeneratorBrand]] String 또는 empty different kinds of async generators를 distinguish하기 위해 사용되는 brand. ECMAScript source text로 declared된 async generators의 [[GeneratorBrand]]는 항상 empty입니다.

27.9.3 AsyncGenerator Abstract Operations

27.9.3.1 AsyncGeneratorRequest Records

AsyncGeneratorRequest는 async generator가 어떻게 resumed되어야 하는지에 대한 information을 store하고, corresponding promise를 fulfilling하거나 rejecting하기 위한 capabilities를 contain하는 데 사용되는 Record value입니다.

이는 다음 fields를 가집니다:

Table 96: AsyncGeneratorRequest Record Fields
Field Name Value Meaning
[[Completion]] Completion Record async generator를 resume하기 위해 사용되어야 하는 Completion Record.
[[Capability]] PromiseCapability Record 이 request와 associated된 promise capabilities.

27.9.3.2 AsyncGeneratorStart ( gen, genBody )

The abstract operation AsyncGeneratorStart takes arguments gen (an AsyncGenerator) and genBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]suspended-start이다.
  2. genContextrunning execution context로 둔다.
  3. genContext의 Generator component를 gen으로 설정한다.
  4. closure를 parameters가 없고 genBody를 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. acGenContextrunning execution context로 둔다.
    2. acGenacGenContext의 Generator component로 둔다.
    3. genBodyParse Node이면, 다음을 수행한다.
      1. resultCompletion(Evaluation of genBody)로 둔다.
    4. Else,
      1. Assert: genBody는 parameters가 없는 Abstract Closure이다.
      2. resultCompletion(genBody())로 둔다.
    5. Assert: 여기로 return한다면, async generator는 exception을 throw했거나 implicit 또는 explicit return 중 하나를 수행했다.
    6. execution context stack에서 acGenContext를 remove하고, execution context stack의 top에 있는 execution contextrunning execution context로 restore한다.
    7. acGen.[[AsyncGeneratorState]]draining-queue로 설정한다.
    8. resultnormal completion이면, resultNormalCompletion(undefined)로 설정한다.
    9. resultreturn completion이면, resultNormalCompletion(result.[[Value]])로 설정한다.
    10. AsyncGeneratorCompleteStep(acGen, result, true)를 수행한다.
    11. AsyncGeneratorDrainQueue(acGen)를 수행한다.
    12. NormalCompletion(undefined)를 반환한다.
  5. genContext의 code evaluation state를, 그 execution context에 대해 evaluation이 resumed될 때 closure가 no arguments로 called되도록 설정한다.
  6. gen.[[AsyncGeneratorContext]]genContext로 설정한다.
  7. gen.[[AsyncGeneratorQueue]]를 new empty List로 설정한다.
  8. unused를 반환한다.

27.9.3.3 AsyncGeneratorValidate ( gen, genBrand )

The abstract operation AsyncGeneratorValidate takes arguments gen (an ECMAScript language value) and genBrand (a String or empty) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(gen, [[AsyncGeneratorContext]])를 수행한다.
  2. RequireInternalSlot(gen, [[AsyncGeneratorState]])를 수행한다.
  3. RequireInternalSlot(gen, [[AsyncGeneratorQueue]])를 수행한다.
  4. gen.[[GeneratorBrand]]genBrand가 아니면, TypeError exception을 throw한다.
  5. unused를 반환한다.

27.9.3.4 AsyncGeneratorEnqueue ( gen, completion, promiseCapability )

The abstract operation AsyncGeneratorEnqueue takes arguments gen (an AsyncGenerator), completion (a Completion Record), and promiseCapability (a PromiseCapability Record) and returns unused. It performs the following steps when called:

  1. requestAsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }로 둔다.
  2. requestgen.[[AsyncGeneratorQueue]]에 append한다.
  3. unused를 반환한다.

27.9.3.5 AsyncGeneratorCompleteStep ( gen, completion, done [ , realm ] )

The abstract operation AsyncGeneratorCompleteStep takes arguments gen (an AsyncGenerator), completion (a Completion Record), and done (a Boolean) and optional argument realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorQueue]]는 empty가 아니다.
  2. nextgen.[[AsyncGeneratorQueue]]의 first element로 둔다.
  3. gen.[[AsyncGeneratorQueue]]에서 first element를 remove한다.
  4. promiseCapabilitynext.[[Capability]]로 둔다.
  5. valuecompletion.[[Value]]로 둔다.
  6. completionthrow completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « value »)를 수행한다.
  7. Else,
    1. Assert: completionnormal completion이다.
    2. realm이 present하면, 다음을 수행한다.
      1. oldRealmrunning execution contextRealm으로 둔다.
      2. running execution contextRealmrealm으로 설정한다.
      3. iteratorResultCreateIteratorResultObject(value, done)로 둔다.
      4. running execution contextRealmoldRealm으로 설정한다.
    3. Else,
      1. iteratorResultCreateIteratorResultObject(value, done)로 둔다.
    4. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
  8. unused를 반환한다.

27.9.3.6 AsyncGeneratorResume ( gen, completion )

The abstract operation AsyncGeneratorResume takes arguments gen (an AsyncGenerator) and completion (a Completion Record) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]suspended-start 또는 suspended-yield 중 하나이다.
  2. genContextgen.[[AsyncGeneratorContext]]로 둔다.
  3. gen.[[AsyncGeneratorState]]executing으로 설정한다.
  4. RunSuspendedContext(genContext, completion)을 수행한다.
  5. unused를 반환한다.

27.9.3.7 AsyncGeneratorUnwrapYieldResumption ( resumptionValue )

The abstract operation AsyncGeneratorUnwrapYieldResumption takes argument resumptionValue (a Completion Record) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. resumptionValuereturn completion이 아니면, ? resumptionValue를 반환한다.
  2. awaitedCompletion(Await(resumptionValue.[[Value]]))로 둔다.
  3. awaitedthrow completion이면, ? awaited를 반환한다.
  4. Assert: awaitednormal completion이다.
  5. ReturnCompletion(awaited.[[Value]])를 반환한다.

27.9.3.8 AsyncGeneratorYield ( arg )

The abstract operation AsyncGeneratorYield takes argument arg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genContext를 실행 중인 실행 컨텍스트라 하자.
  2. Assert: genContext는 제너레이터의 실행 컨텍스트이다.
  3. gengenContext의 Generator 컴포넌트 값이라 하자.
  4. Assert: GetGeneratorKind()는 async이다.
  5. completionNormalCompletion(arg)이라 하자.
  6. Assert: 실행 컨텍스트 스택에는 최소 두 개의 요소가 있다.
  7. previousContext를 실행 컨텍스트 스택의 위에서 두 번째 요소라 하자.
  8. previousRealmpreviousContextRealm이라 하자.
  9. AsyncGeneratorCompleteStep(gen, completion, false, previousRealm)을 수행한다.
  10. queuegen.[[AsyncGeneratorQueue]]라 하자.
  11. queue가 비어 있지 않으면,
    1. NOTE: 실행은 제너레이터를 일시 중단하지 않고 계속된다.
    2. toYieldqueue의 첫 번째 요소라 하자.
    3. resumptionValueCompletion(toYield.[[Completion]])이라 하자.
    4. AsyncGeneratorUnwrapYieldResumption(resumptionValue)를 반환한다.
  12. gen.[[AsyncGeneratorState]]suspended-yield로 설정한다.
  13. resumptionValueCompletion(RunCallerContext(undefined))이라 하자.
  14. AsyncGeneratorUnwrapYieldResumption(resumptionValue)를 반환한다.

27.9.3.9 AsyncGeneratorAwaitReturn ( gen )

The abstract operation AsyncGeneratorAwaitReturn takes argument gen (an AsyncGenerator) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
  2. queuegen.[[AsyncGeneratorQueue]]로 둔다.
  3. Assert: queue는 empty가 아니다.
  4. nextqueue의 first element로 둔다.
  5. completionCompletion(next.[[Completion]])으로 둔다.
  6. Assert: completionreturn completion이다.
  7. promiseCompletionCompletion(PromiseResolve(%Promise%, completion.[[Value]]))로 둔다.
  8. promiseCompletionabrupt completion이면, 다음을 수행한다.
    1. AsyncGeneratorCompleteStep(gen, promiseCompletion, true)를 수행한다.
    2. AsyncGeneratorDrainQueue(gen)를 수행한다.
    3. unused를 반환한다.
  9. Assert: promiseCompletionnormal completion이다.
  10. promisepromiseCompletion.[[Value]]로 둔다.
  11. fulfilledClosure를 parameters (value)를 가지고 gen을 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
    2. resultNormalCompletion(value)로 둔다.
    3. AsyncGeneratorCompleteStep(gen, result, true)를 수행한다.
    4. AsyncGeneratorDrainQueue(gen)를 수행한다.
    5. NormalCompletion(undefined)를 반환한다.
  12. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « »)로 둔다.
  13. rejectedClosure를 parameters (reason)를 가지고 gen을 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
    2. resultThrowCompletion(reason)으로 둔다.
    3. AsyncGeneratorCompleteStep(gen, result, true)를 수행한다.
    4. AsyncGeneratorDrainQueue(gen)를 수행한다.
    5. NormalCompletion(undefined)를 반환한다.
  14. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)로 둔다.
  15. PerformPromiseThen(promise, onFulfilled, onRejected)를 수행한다.
  16. unused를 반환한다.

27.9.3.10 AsyncGeneratorDrainQueue ( gen )

The abstract operation AsyncGeneratorDrainQueue takes argument gen (an AsyncGenerator) and returns unused. generator의 AsyncGeneratorQueue를 return completion을 holding하는 AsyncGeneratorRequest를 encounters할 때까지 drains합니다. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
  2. queuegen.[[AsyncGeneratorQueue]]로 둔다.
  3. Repeat, while queue is not empty,
    1. nextqueue의 first element로 둔다.
    2. completionCompletion(next.[[Completion]])으로 둔다.
    3. completionreturn completion이면, 다음을 수행한다.
      1. AsyncGeneratorAwaitReturn(gen)을 수행한다.
      2. unused를 반환한다.
    4. completionnormal completion이면, 다음을 수행한다.
      1. completionNormalCompletion(undefined)로 설정한다.
    5. AsyncGeneratorCompleteStep(gen, completion, true)를 수행한다.
  4. gen.[[AsyncGeneratorState]]completed로 설정한다.
  5. unused를 반환한다.

27.10 AsyncFunction 객체

AsyncFunctions는 보통 AsyncFunctionDeclaration, AsyncFunctionExpression, AsyncMethod, 및 AsyncArrowFunction을 평가하여 생성되는 functions입니다. 또한 %AsyncFunction% intrinsic을 호출하여 생성될 수도 있습니다.

27.10.1 AsyncFunction Constructor

AsyncFunction constructor는:

  • %AsyncFunction%입니다.
  • Function의 subclass입니다.
  • constructor가 아니라 function으로 호출될 때 새 AsyncFunction을 생성하고 초기화합니다. 따라서 function call AsyncFunction(…)은 같은 arguments를 가진 object creation expression new AsyncFunction(…)과 동등합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. 지정된 AsyncFunction behaviour를 상속하려는 subclass constructors는 built-in async function behaviour에 필요한 internal slots를 가진 subclass instance를 생성하고 초기화하기 위해 AsyncFunction constructor에 대한 super call을 포함해야 합니다. async function objects를 정의하는 모든 ECMAScript syntactic forms는 AsyncFunction의 direct instances를 생성합니다. AsyncFunction subclasses의 instances를 생성하는 syntactic means는 없습니다.

27.10.1.1 AsyncFunction ( ...paramArgs, bodyArg )

마지막 argument(있다면)는 async function의 body(executable code)를 지정합니다. preceding arguments는 formal parameters를 지정합니다.

이 function은 호출될 때 다음 steps를 수행합니다:

  1. activeFunc를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, async, paramArgs, bodyArg)를 반환한다.
Note
20.2.1.1NOTE를 참조하십시오.

27.10.2 AsyncFunction Constructor의 Properties

AsyncFunction constructor는:

  • Function constructor에서 inherit하는 standard built-in function object입니다.
  • value가 %Function%[[Prototype]] internal slot을 가집니다.
  • value가 1𝔽"length" property를 가집니다.
  • value가 "AsyncFunction""name" property를 가집니다.
  • 다음 properties를 가집니다:

27.10.2.1 AsyncFunction.prototype

AsyncFunction.prototype의 initial value는 AsyncFunction prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.10.3 AsyncFunction Prototype Object의 Properties

AsyncFunction prototype object는:

27.10.3.1 AsyncFunction.prototype.constructor

AsyncFunction.prototype.constructor의 initial value는 %AsyncFunction%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.10.3.2 AsyncFunction.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "AsyncFunction"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.10.4 AsyncFunction Instances

모든 AsyncFunction instance는 ECMAScript function object이며 Table 26에 listed된 internal slots를 가집니다. 그러한 모든 instances의 [[IsClassConstructor]] internal slot의 value는 false입니다. AsyncFunction instances는 constructors가 아니며 [[Construct]] internal method를 가지지 않습니다. AsyncFunction instances는 constructable이 아니므로 prototype property를 가지지 않습니다.

각 AsyncFunction instance는 다음 own properties를 가집니다:

27.10.4.1 length

20.2.4.1에 given된 Function instances의 "length" property에 대한 specification은 AsyncFunction instances에도 적용됩니다.

27.10.4.2 name

20.2.4.2에 given된 Function instances의 "name" property에 대한 specification은 AsyncFunction instances에도 적용됩니다.

27.10.5 Async Functions Abstract Operations

27.10.5.1 AsyncFunctionStart ( promiseCapability, asyncFuncBody )

The abstract operation AsyncFunctionStart takes arguments promiseCapability (a PromiseCapability Record) and asyncFuncBody (a FunctionBody Parse Node, an ExpressionBody Parse Node, or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. runningContextrunning execution context로 둔다.
  2. asyncContextrunningContext의 copy로 둔다.
  3. NOTE: execution state를 copy하는 것은 AsyncBlockStart가 its execution을 resume하기 위해 required된다. currently executing context를 resume하는 것은 ill-defined이다.
  4. AsyncBlockStart(promiseCapability, asyncFuncBody, asyncContext)를 수행한다.
  5. unused를 반환한다.

27.10.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext )

The abstract operation AsyncBlockStart takes arguments promiseCapability (a PromiseCapability Record), asyncBody (a Parse Node or an Abstract Closure with no parameters), and asyncContext (an execution context) and returns unused. It performs the following steps when called:

  1. closure를 parameters가 없고 promiseCapabilityasyncBody를 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. acAsyncContextrunning execution context로 둔다.
    2. asyncBodyParse Node이면, 다음을 수행한다.
      1. resultCompletion(Evaluation of asyncBody)로 둔다.
    3. Else,
      1. Assert: asyncBody는 parameters가 없는 Abstract Closure이다.
      2. resultCompletion(asyncBody())로 둔다.
    4. Assert: 여기로 return한다면, async function은 exception을 throw했거나 implicit 또는 explicit return을 수행했다; all awaiting is done.
    5. execution context stack에서 acAsyncContext를 remove하고, execution context stack의 top에 있는 execution contextrunning execution context로 restore한다.
    6. resultnormal completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
    7. Else if resultreturn completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »)를 수행한다.
    8. Else,
      1. Assert: resultthrow completion이다.
      2. Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »)를 수행한다.
    9. NormalCompletion(unused)를 반환한다.
  2. asyncContext의 code evaluation state를, 그 execution context에 대해 evaluation이 resumed될 때 closure가 no arguments로 called되도록 설정한다.
  3. result를 ! RunSuspendedContext(asyncContext, NormalCompletion(empty))로 둔다.
  4. Assert: resultunused이다.
  5. NOTE: result values의 possible sources는 Await이거나, async function이 anything을 await하지 않는 경우 위의 step 1.i이다.
  6. unused를 반환한다.

27.10.5.3 Await ( arg )

The abstract operation Await takes argument arg (an ECMAScript language value) and returns either a normal completion containing either an ECMAScript language value or empty, or a throw completion. It performs the following steps when called:

  1. asyncContext를 실행 중인 실행 컨텍스트라 하자.
  2. promise를 ? PromiseResolve(%Promise%, arg)라 하자.
  3. fulfilledClosureasyncContext를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (v)를 갖는 새로운 Abstract Closure라 하자.
    1. Completion(RunSuspendedContext(asyncContext, NormalCompletion(v)))을 수행한다.
    2. NOTE: RunSuspendedContext가 반환한 Completion Record는 의도적으로 무시된다.
    3. NormalCompletion(undefined)을 반환한다.
  4. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « »)라 하자.
  5. rejectedClosureasyncContext를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (reason)를 갖는 새로운 Abstract Closure라 하자.
    1. Completion(RunSuspendedContext(asyncContext, ThrowCompletion(reason)))을 수행한다.
    2. NOTE: RunSuspendedContext가 반환한 Completion Record는 의도적으로 무시된다.
    3. NormalCompletion(undefined)을 반환한다.
  6. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)라 하자.
  7. PerformPromiseThen(promise, onFulfilled, onRejected)을 수행한다.
  8. RunCallerContext(empty)를 반환한다.