早速ですが、以下のコードを見てください。(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
の利用シーンは限られている気はしますが、何か面白い使い方ができたらいいですね。
何かあればコメント欄またはツイッターまでお願いします。
...await pic.twitter.com/ChYtTta1BX
— あかめ@無職.js (@akameco) November 9, 2017
...await/catch 🤔 pic.twitter.com/yxKj5KLvmp
— あかめ@無職.js (@akameco) November 9, 2017
とんでもない邪悪が産まれた ...await with async/catch pic.twitter.com/W8ADwDNUq9
— あかめ@無職.js (@akameco) November 10, 2017