0
0

More than 1 year has passed since last update.

JavaScript:Promiseを使い、並行処理のサンプル

Last updated at Posted at 2023-08-24

前書

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を返し、成功/失敗を判断。
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