📖
training
  • index
  • CSS
  • JavaScript
    • DOM イベント
    • document.write
    • window.alert
    • console.log
    • ステートメント
    • データ型
    • for
    • オブジェクト
    • リテラル
    • 変数
    • 宣言
    • スコープ
    • 型変換
    • 配列
    • Strictモード
    • 演算子
    • if
    • switch
    • 繰り返し
    • for
    • for...in
    • for...of
    • for await...of
    • while
    • do...while
    • 関数
    • Element インターフェイス
    • Documentインターフェイス
GitBook提供
このページ内
  • 構文
  • 例

役に立ちましたか?

  1. JavaScript

for await...of

非同期(と同期)の反復オブジェクトを繰り返して処理するループを作ります。 対象の反復オブジェクトは、ビルトインの String、Array、配列様オブジェクトarguments、NodeList 等)、TypedArray、Map、Set、 さらに、ユーザーが定義した****非同期・同期の反復オブジェクトが含まれます。 オブジェクトの各プロパティの値に対して実行されるステートメントを使用してカスタム反復フックを呼び出します。

構文

for await (variable of iterable) {
  statement
}
  • variable 反復ごとに、異なるプロパティの値が variable に割り当てられます。

  • iterable 反復可能プロパティが反復処理されるオブジェクトです。

例

const names = ['a', 'b', 'c', 'd'];

for await (let name of names) {
  const result = await fetch(`https://someurl.com/names/${name}`);
  console.log(result.json());
}

console.log('全ての api 通信完了');

これの結果は

$ <json result 'a'...>
$ <json result 'b'...>
$ <json result 'c'...>
$ <json result 'd'...>
$ 全ての api 通信完了

になる。

もしこれをfor await...ofを使わずに

const names = ['a', 'b', 'c', 'd'];

names.forEach(async (name) => {
  const result = await fetch(`https://someurl.com/names/${name}`);
  console.log(result.json());
});

console.log('全ての api 通信完了');

とすれば、

$ 全ての api 通信完了
$ <json result 'a'...>
$ <json result 'b'...>
$ <json result 'c'...>
$ <json result 'd'...>

こんな結果になる。

前へfor...of次へwhile

最終更新 5 年前

役に立ちましたか?