LoginSignup
4
4

More than 5 years have passed since last update.

JavaScript で Promiseを返す非同期/同期的に動作する複数の関数を並列に呼び出し、その結果を取得する

Last updated at Posted at 2018-03-31

JavaScript で Promiseを返す関数を並列に呼び出しその結果を取得するには、Promise.all と Array#map を併用し、
const values = await Promise.all([fn, fn, fn].map(fn => fn()) のようにします。

(async() => {
  const fn = (index) => {
    return new Promise(resolve => {
      setTimeout(() => resolve(index), 1000 * index);
    });
  };

  const process = async() => {
    console.log(`fn call begin`);

    const source = [ fn, fn, fn ];
    const values = await Promise.all(source.map((fn, index) => {
      console.log(`fn[${index}] called`);
      return fn(index);
    }));

    console.log(`fn call end`);

    return values; // [ 0, 1, 2 ]
  };

  console.log(`values ${await process()}`); // log(`values 0,1,2`)
})();
fn call begin
fn[0] called
fn[1] called
fn[2] called
fn call end
values 0,1,2
  • イテレータや Array like Object を Promise.all に渡す場合は、 await Promise.all(Array.from(iter).map(...)) とします。

  • 同期関数の結果を Promise.all に渡す場合は Promise.resolve(sync_fn()) のようにして Promise でラップします。

4
4
1

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