Chapter 03

実例で学ぶPromise (1)

いーちゃん
いーちゃん
2021.08.15に更新

Promiseを返す関数といえばブラウザには fetchがあります。

fetch("https://httpstat.us/200")
  .then(result => result.text()) // fetch関数はtextメソッドなどを返すので呼び出す
  .then(text => console.log(text)) // thenもまたthenを返すのでつなげる
  .catch(reason => console.error(reason)); // rejectされたとき
// コンソールに 200 OK が出てくる

本質からは外れますが、fetch関数はHTTPステータスのエラー(404, 500など)があってもrejectはしません。rejectされるのは、CORS関連のエラーや、ネットワーク接続のエラーなどが発生したときに限られます。

fetch("https://httpstat.us/418")
  .then(result => result.text()) // 400番台だからrejectと思いきやfulfilled。
  .then(text => console.log(text))
  .catch(reason => console.error(reason)); // ネットワークエラーをcatch
// コンソールに 418 I'm a teapot が出てくる (RFC2324)