Skip to content

Latest commit

 

History

History
73 lines (66 loc) · 2.48 KB

82e3ce1f837cfe96e873.md

File metadata and controls

73 lines (66 loc) · 2.48 KB
title emoji type topics published published_at
then/catch めっちゃ便利じゃね?(今更)
🙄
idea
javascript
ポエム
true
2020-11-26 16:43

await/catch を使うときの early return という記事を書いたばかりなのですが、ちょっと気に入った書き方を見つけたのでまた書きます

今まで逐次実行するときには

async () => {
  const res = await fetch('/endpoint')
  const json = await res.json()
  const text = json.text
  await fetch('/endpoint', {
    method: 'POST',
    body: text
  })
  
}

みたいに書いていたのですが、 じゃあ fetch がコケたらどうするの? と…

async () => {
  const res = await fetch('/endpoint')
    .catch((err) => {
      throw err
    })
  const json = await res.json()
  const text = json.text
  await fetch('/endpoint', {
    method: 'POST',
    body: text
  })
  
}

まあいっかって思ってたのですが、なんかモヤモヤが残る書き方ですよね? json() がコケたら? text がなかったら?? どんどん汚くなるのです

これが、then/catch で気持ちよく書けることに気がつきました(今更)

async () => {
  const json = await fetch('/endpoint')
    .then(async (res) => await res.json())
    .then((json) => json.text)
    .then(async (text) => await fetch('/endpoint', {
      method: 'POST',
      body: text
    }))
    .then(async (res) => await res.json())
    .catch(console.error)
  
}

今までthenのコールバックにasync関数を書いたら汚くなりそうだなと思って避けていたり、 そもそもthen/catch を await しようって発想がなかったりしたこともあってモヤモヤしていました

でも、元コードでawaitしている1行をすべてthenで分割していく形で書き換えればそんなに汚くならないし、 戻り値をリレーするプロセスをthenで繋いで、その一連のカタマリをawaitして並べていけばしっかり関数の最後まできれいに逐次実行していけそうです しかもfinallyも使えてとっても捗る (そしたらそのカタマリの間でearly returnしたいときは結局catch内でthrowかな…)

こんなしょーもない記事、公開しようか迷いましたが、 同じような人がいるかもしれないし(?)非同期処理初心者にはいいかなと思って…