戻る

Promise.all()
Promise.all()

複数のPromiseをまとめます。複数の独立した非同期タスクがすべて完了してから次の処理に進む準備をします。Promiseが成功すると結果を配列として返します。失敗するとエラーを返します。

[サンプル]
copy
//[test 1]
const time10 = async () => { await sleep(10); console.log('10s'); };
const time30 = async () => { await sleep(30); console.log('30s'); };
const time60 = async () => { await sleep(60); console.log('60s'); };
Promise.all([
	time30,
	time60,
	time10
	])
    .then(function(messege){
        console.log(messege)
    })
    .catch(function(reason) {
        console.log(reason)
    });

console.log("--------------");

//[test 2]
const func = (t) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (t > 0) {
        resolve(`${t}sec`);
      } else {
        reject('specify second');
      }
    }, t * 1000);
  })
}

Promise.all([func(3), func(1), func(2)])
  .then((result) => {
    console.log(result);
  })
  .catch((result) => {
    console.log(result);
  });

//[result]
/*
--------------
(3) [ƒ, ƒ, ƒ]
0: async () => { await sleep(30); console.log('30s'); }
1: async () => { await sleep(60); console.log('60s'); }
2: async () => { await sleep(10); console.log('10s'); }
length: 3
(3) ['3sec', '1sec', '2sec']
0: "3sec"
1: "1sec"
2: "2sec"
length: 3
*/

Promise.allに指定したメソッドを配列で指定します。
すべての処理を終了するとthen
途中で失敗するとcatch
を実行します。

非同期処理の実行速度向上
直列処理(順番に実行)ではなく並列処理(同時に実行)を行うことで、
全体の実行時間を短縮できます。

依存関係のある処理には使わない
1つ目のAPIの結果を2つ目のAPIで利用するなど、
非同期処理が互いに依存している場合は Promise.all() を使わず、
await を使って順番に処理する必要があります。

エラーハンドリング
1つのPromiseが失敗すると全体が失敗するため、
部分的な失敗を許容したい場合はPromise.allSettled()を使用します。




戻る


著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。