Promiseメモ
Promiseとは
ある処理が完了したら呼ばれる関数
Promiseは3つの状態を持っている
・ unresolved(実行待ち)
・ resolved(成功)
・ rejected(失敗)
thenで成功時の処理を実行
catchで失敗時の処理を実行する
promise = new Promise((resolve,reject)=>{ //成否処理 //resolve();成功時の処理を実行(thenが宣言されている処理へ) //reject();失敗時の処理を実行(catchが宣言されている処理へ) }); promise .then(() => console.log("成功")) .then(() => console.log("---処理---")) .catch(() => console.log("失敗"));
fetchを使う
fetchを使ってリクエストを行う
fetchでurlを指定するとPromiseが返却値として返ってくる為
then,chatchを使用することができる
const url = "https://jsonplaceholder.typicode.com/posts/"; fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(error=>console.log(`エラー:${error}`));
fetchの注意点
Ajaxなどはステータスコードが300以上の場合chatchに入るが、
fetchの場合ネットワークのリクエストが失敗した場合のみcatchに入る