for await...of 文は非同期(と同期)の反復オブジェクトを繰り返して処理するループを作ります。対象の反復オブジェクトは、ビルトインの String、Array、配列様オブジェクト( arguments、NodeList 等)、TypedArray、Map、Set、さらに、ユーザーが定義した非同期・同期の反復オブジェクトが含まれます。オブジェクトの各プロパティの値に対して実行されるステートメントを使用してカスタム反復フックを呼び出します。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
for await (variable of iterable) {
statement
}
variable- 反復ごとに、異なるプロパティの値が variable に割り当てられます。
iterable- 反復可能プロパティが反復処理されるオブジェクトです。
非同期反復オブジェクトを繰り返し処理する
非同期反復可能プロトコルを明示的に実装しているオブジェクトを反復処理することができます:
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
非同期ジェネレータを繰り返し処理する
非同期反復可能プロトコルを実装している async generator であれば、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
仕様
| 仕様書 | 策定状況 | コメント |
|---|---|---|
| ECMAScript (ECMA-262) ECMAScript Language: The for-in, for-of, and for-await-of Statements の定義 |
現行の標準 |
ブラウザー実装状況
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| デスクトップ | モバイル | サーバー | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
for await...of | Chrome 完全対応 63 | Edge 完全対応 79 | Firefox 完全対応 57 | IE 未対応 なし | Opera 完全対応 50 | Safari 完全対応 11 | WebView Android 完全対応 63 | Chrome Android 完全対応 63 | Firefox Android 完全対応 57 | Opera Android 完全対応 46 | Safari iOS 完全対応 11 | Samsung Internet Android 完全対応 8.0 | nodejs
完全対応
10.0.0
|
凡例
- 完全対応
- 完全対応
- 未対応
- 未対応
- ユーザーが明示的にこの機能を有効にしなければなりません。
- ユーザーが明示的にこの機能を有効にしなければなりません。