0
0

More than 1 year has passed since last update.

非同期関数のループ処理 - Part4(Promise.allを使用)

Last updated at Posted at 2021-09-20

他の処理方法との違い

Part1ではforEach + async/await、Part2ではforLoop + async/await、Part3ではforLoop + promise/thenメソッドを使いましたが、今回は、伝家の宝刀、Promise.all()を使用してテストします!

ループ処理の内容

フェイク非同期関数(fakeDatabaseQuery)を作成し、その関数がpromiseオブジェクトをリターンする形にします。

また、ファンクションprocessArrayの中では、Array.prototype.map()を使用して、Promiseオブジェクトがアレイに詰め込まれた100回分の処理のひな型(const promises)を作り、それに対して、Promise.all()で100回分の処理を一気に行います。

その際、順番が変わらないので、ソートをかける必要はありません。

まとめ

このような非同期関数をループ実行する場合、Promise.allを使ったsyntax(構文)は、シンプルかつ処理が高速ということで、最もおすすめな方法です。

その他

下記のサンプルコードは、Node.js v14.15.5でテストしたものです。また、私が利用している環境(Ubuntu + Node.js)では、処理時間は115ms ~ 120msとなりました。

サンプルコード

console.time();

//forLoopを使って、整数1~100が入っているarrayを作ります
let arrayN = [];
const arrayLength = 100;
for (let i = 0; i < arrayLength; i++) {
    arrayN.push(i+1);
}

//データベース検索を偽装したフェイク非同期関数
function fakeDatabaseQuery (index) {
    //ランダム関数により、2桁の整数を生成
    const elapse = Math.floor(Math.random() * 100);
    return new Promise(function(resolve, reject) {
        const result = {
            index:index,
            elapse:elapse
        }
        //setTimeoutを使い、意図的に遅延を作ります。
        setTimeout(() => resolve(result), elapse);
    });
}

async function processArray(array) {
    //mapを使って、100セットのプロミスオブジェクトが詰め込まれたアレイpromisesを作成
    const promises = array.map(fakeDatabaseQuery);
    //Promise.all()を使って、100セットの処理を同時に開始
    //awaitが効いているので、すべてfulfilledになってから、fakeSearchResultへ値を代入
    const fakeSearchResult = await Promise.all(promises);

    console.log('fakeSearchResult', fakeSearchResult);
    console.log('Done!');
    console.timeEnd();
}

processArray(arrayN);

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