Qiita Conference 2025

ミノ駆動 (@MinoDriven)

プロフェッショナルとしての成長──「問題の深掘り」が導く真のスキルアップ

3
5

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.

...await: 配列の中でawaitを使い非同期処理をする

Posted at

早速ですが、以下のコードを見てください。(LTSであるv8.9.1で動作確認済)

const fn = async () => [1, 2, 3]

const main = async () => {
  const list = [...await fn(), ...await fn()]
  console.log(list)
  // [1, 2, 3, 1, 2, 3]
}

main()

配列の中でawaitとして得た配列をを...で展開しています。
...awaitなんて実際出番ないだろと思うかも知れませんが、GoogleChrome/puppeteerでも使われています。

さて、伝えたいことはこれだけですが、それではアレなので、async/catchと一緒に使ってみましょう。

async/catchについては、以下の記事を参照して下さい。

async関数においてtry/catchではなくawait/catchパターンを活用する

さて、配列を返す関数をランダムでエラーを起こすようにしてみます。

const fn = async () =>
  Math.random() > 0.5
    ? [1, 2, 3]
    : Promise.reject(new Error('hello from array!!!'))

const main = async () => {
  const list = [
    ...(await fn().catch(err => [])),
    ...(await fn().catch(err => []))
  ]
  console.log(list)
  // => []
  // or => [1, 2, 3]
  // or => [1, 2, 3, 1, 2, 3]
}

main()

[][1,2,3][1,2,3,1,2,3]と配列の中で非同期のエラー処理が出来ます。

少し邪悪にしてみます。awaitはthenも待てるので、普通に非同期な処理を配列の中で書くことが出来ます。

const fn = async () =>
  Math.random() > 0.5
    ? [1, 2, 3]
    : Promise.reject(new Error('hello from array!!!'))

const main = async () => {
  const add1 = x => x + 1
  const map = fn => x => x.map(fn)

  const list = [
    ...(await fn().catch(err => console.log(err.message) || [])),
    ...(await fn()
      .then(map(add1))
      .catch(err => []))
  ]

  console.log(list)
  // => hello from array!!!
  // => [ 2, 3, 4 ]
}

main()

おわりに

...awaitの利用シーンは限られている気はしますが、何か面白い使い方ができたらいいですね。
何かあればコメント欄またはツイッターまでお願いします。

3
5
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?