LoginSignup
1
0

More than 1 year has passed since last update.

TypescriptでPromise.allを使用したループ処理

Posted at

Typescriptでは、非同期処理を簡単に扱うことができます。
特に、複数の非同期処理を並列実行する場合には、Promise.allを使用することが推奨されます。

今回は、猫の数を数える例を用いて、Promise.allを使用したループ処理について説明します。

例:猫の数を数える処理

まず、猫の数を数える処理を非同期処理として実装します。以下の例では、1秒間待ってから、猫の数を返す非同期処理を定義しています。

function countCats(): Promise<number> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(3);
    }, 1000);
  });
}

次に、任意の数のPromiseオブジェクトを生成する関数を定義します。

function createPromises(): Promise<number>[] {
  const promises: Promise<number>[] = [];
  for (let i = 0; i < 5; i++) {
    promises.push(countCats());
  }
  return promises;
}

最後に、Promise.allを使用して、生成した複数のPromiseオブジェクトを並列実行します。

Promise.all(createPromises()).then((results) => {
  let total = 0;
  for (const result of results) {
    total += result;
  }
  console.log(`合計猫の数: ${total}匹`);
});

この例では、5つのPromiseオブジェクトを生成して、Promise.allを使用して並列実行しています。
すべてのPromiseオブジェクトが完了したら、then関数が実行されます。then関数では、結果を加算して合計猫の数を出力しています。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0