前書
- 自分勉強のメモ、ご参考まで
- 参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Promise.allのサンプル
サンプルソース:
MultiAsyncCalls.js
var aaa = aaa || {};
(function (global) {
var _ = aaa; // namespace
var asyncCall1 = function () {
return new Promise((resolve) => {
setTimeout(() => {
console.log('asyncCall 1 ...');
resolve('resolved');
}, 5000);
});
};
var asyncCall2 = function () {
return new Promise((resolve) => {
setTimeout(() => {
console.log('asyncCall 2 ...');
resolve('resolved');
}, 4000);
});
};
var asyncAll = function () {
const p1 = asyncCall1();
const p2 = asyncCall2();
return Promise.all([p1, p2]);
};
_.main = async function () {
await asyncCall1();
await asyncCall2();
console.log('-----------------');
await asyncAll();
console.log('over');
return 0;
};
}(this));
aaa.main();
実行結果:
// 順番実行結果
asyncCall 1 ... // 5秒
asyncCall 2 ... // 9秒
---------------------------
// 並行実行結果
asyncCall 2 ... // 4秒
asyncCall 1 ... // 5秒
over
後書
- Promise.all:すべて成功完了なら、成功完了になる。いずれか失敗完了なら、失敗完了。
- Promise.allSettled:すべて実行完了を待つ。結果status,value,reasonを返し、成功/失敗を判断。