LoginSignup
17
20

More than 5 years have passed since last update.

async-await内で並列処理

Last updated at Posted at 2017-06-16

async-await内で並列的に実行したい場合

function sleepAndSay(time: number, msg: string): Promise<void> {
    return new Promise<void>(resolve => {
        setTimeout(() => {
            console.log(msg)
            resolve();
        }, time);
    });
}

async function main() {
    await sleepAndSay(200, 'test1')
    await sleepAndSay(100, 'test2')
    await Promise.all([
        (async () => {
            await sleepAndSay(50, 'in promise.all 1-1');
            await sleepAndSay(40, 'in promise.all 1-2');
            await sleepAndSay(40, 'in promise.all 1-3');
            return;
        })(),
        (async () => {
            await  sleepAndSay(30, 'in promise.all 2-1');
            await  sleepAndSay(20, 'in promise.all 2-2');
            await  sleepAndSay(20, 'in promise.all 2-3');
            return;
        })(),
    ])

    await sleepAndSay(100, 'test3')

}

実行結果

test1
test2
in promise.all 2-1
in promise.all 1-1
in promise.all 2-2
in promise.all 2-3
in promise.all 1-2
in promise.all 1-3
test3

目的通り動くけどPromise.allはpromiseを受け取る。
async はpromiseを 返す 関数を作るので all内で実行する必要があり、(が少しうざい。

改善案としてpararels関数を作る

function pararels(...promises: (() => Promise<any>)[]) {
  return Promise.all(promises.map(p => p()));
}

async function main2() {
    await sleepAndSay(200, 'test1')
    await sleepAndSay(100, 'test2')
    await pararels(
        async () => {
            await sleepAndSay(50, 'in promise.all 1-1');
            await sleepAndSay(40, 'in promise.all 1-2');
            await sleepAndSay(40, 'in promise.all 1-3');
            return;
        },
        async () => {
            await  sleepAndSay(30, 'in promise.all 2-1');
            await  sleepAndSay(20, 'in promise.all 2-2');
            await  sleepAndSay(20, 'in promise.all 2-3');
            return;
        },
    )

    await sleepAndSay(100, 'test3')

}

実行結果

test1
test2
in promise.all 2-1
in promise.all 1-1
in promise.all 2-2
in promise.all 2-3
in promise.all 1-2
in promise.all 1-3
test3

少し楽になった

17
20
2

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
17
20