for await...of

The for await...of statement creates a loop iterating over async iterable objects as well as on sync iterables, including: built-in String, ArrayArray-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined async/sync iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

Syntax

for await (variable of iterable) {
  statement
}
variable
On each iteration a value of a different property is assigned to variable.
iterable
Object whose iterable properties are to be iterated over.

Iterating over async iterables

You can also iterate over an object that explicitly implements async iterable protocol:

var asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }

        return Promise.resolve({ done: true });
      }
    };
  }
};

(async function() {
   for await (num of asyncIterable) {
     console.log(num);
   }
})();

// 0
// 1
// 2

Iterating over async generators

Since async generators implement async Iterator protocol, they can be looped using for await...of

async function* asyncGenerator() {
  var i = 0;
  while (i < 3) {
    yield i++;
  }
}

(async function() {
  for await (num of asyncGenerator()) {
    console.log(num);
  }
})();
// 0
// 1
// 2

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
The definition of 'ECMAScript Language: The for-in, for-of, and for-await-of Statements' in that specification.
Draft  

Browser compatibility

 

See also

Document Tags and Contributors

Contributors to this page: Sheppy, wmsbill
Last updated by: Sheppy,