3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「Arrayの中身に対して繰り返し非同期処理を実行する」処理を同期的に実行する時にArray.prototype.map()を使う話

Posted at

async関数がPromiseをreturnする事を利用して内部でawaitでpendingさせといてmapの返り値をそのままPromise.all()にブチ込むのよくやる。

index.js
(async () => {
  try {
    console.log("begin");
    console.log(Date.now());
    const p = [1, 2, 3].map(async v => {
      await new Promise((s, j) => {
        setTimeout(() => {
          s(true);
        }, 1000 * v);
      });
    });
    console.log(p);
    await Promise.all(p);
    console.log(p);
    console.log("end");
    console.log(Date.now());
  } catch (e) {
    console.error(e);
  }
})();
$ node index.js
begin
1532527193864
[ Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> } ]
[ Promise { undefined },
  Promise { undefined },
  Promise { undefined } ]
end
1532527196868
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?