LoginSignup
7
5

More than 3 years have passed since last update.

並列処理数を指定できる Promise.all の実装

Last updated at Posted at 2019-05-08

実装

const promiseAllWithConcurrencyLimit =
  async <T>(promises: (() => Promise<T>)[], concurrency: number) => {
    const results: T[] = []
    let idx = 0
    await Promise.all(Array.from({ length: concurrency }).map(async () => {
      while (true) {
        const cur = idx++
        const task = promises[cur]
        if (!task) return
        results[cur] = await task()
      }
    }))
    return results
  }

記事を書くまでの経緯

こちらの記事の実装の場合

[6秒かかる処理, 2秒かかる処理, 2秒かかる処理, 2秒かかる処理]concurrency = 2 で実行すると 8 秒かかります。

上記の実装の場合 6 秒ですみます。

解説

Promiseconcurrency の指定数生成する。

Promise は下記を行う。

  1. promises に処理が残っていなかったら終了。
  2. promises から処理を取り出して実行する。
  3. 1. に戻る。

これにより、 Promise の数だけ並行して処理が走る。
Promise 内では await の指定により同期的に走るため数を超えない )

追記 2020-06-04

並列処理数を指定できてキャンセルできる Promise.all の実装 を書きました

7
5
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
7
5