for await...of

翻译不完整。 请帮助我们翻译这篇文章!

for await...of 语句会在异步或者同步可迭代对象上创建一个迭代循环,包括 StringArrayArray-like 对象(比如arguments 或者NodeList),TypedArrayMap, Set和自定义的异步或者同步可迭代对象。其会调用自定义迭代钩子,并为每个不同属性的值执行语句

语法

for await (variable of iterable) {
  statement
}
variable
在每次迭代中,将不同属性的值分配给变量。变量有可能以constlet, 或者 var来声明。
iterable
被迭代枚举其属性的对象。与 for...of 相比,这里的对象可以返回 Promise,如果是这样,那么 variable 将是 Promise 所包含的值,否则是值本身。

迭代异步可迭代对象

你还可以迭代一个明确实现异步迭代协议的对象:

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

迭代异步生成器 

异步生成器已经实现了异步迭代器协议, 所以可以用 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

有关使用for await... of考虑迭代API中获取数据的异步 generator 更具体的例子。这个例子首先为一个数据流创建了一个异步 generator,然后使用它来获得这个API的响应值的大小。

async function* streamAsyncIterator(stream) {
  const reader = stream.getReader();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        return;
      }
      yield value;
    }
  } finally {
    reader.releaseLock();
  }
}
// 从url获取数据并使用异步 generator 来计算响应值的大小
async function getResponseSize(url) {
  const response = await fetch(url);
  // Will hold the size of the response, in bytes.
  let responseSize = 0;
  // 使用for-await-of循环. 异步 generator 会遍历响应值的每一部分
  for await (const chunk of streamAsyncIterator(response.body)) {
    // Incrementing the total response length.
    responseSize += chunk.length;
  }
  
  console.log(`Response Size: ${responseSize} bytes`);
  // expected output: "Response Size: 1071472"
  return responseSize;
}
getResponseSize('https://jsonplaceholder.typicode.com/photos');

规范

Specification Status Comment
ECMAScript (ECMA-262)
ECMAScript Language: The for-in, for-of, and for-await-of Statements
Living Standard
ECMAScript 2018 (ECMA-262)
ECMAScript Language: The for-in, for-of, and for-await-of Statements
Standard

浏览器兼容

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
for await...ofChrome Full support 63Edge Full support 79Firefox Full support 57IE No support NoOpera Full support 50Safari Full support 11WebView Android Full support 63Chrome Android Full support 63Firefox Android Full support 57Opera Android Full support 46Safari iOS Full support 11Samsung Internet Android Full support 8.0nodejs Full support 10.0.0
Full support 10.0.0
No support 8.10.0 — 10.0.0
Disabled
Disabled From version 8.10.0 until version 10.0.0 (exclusive): this feature is behind the --harmony-async-iteration runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接