昨天第一次用 fetch() 去外面拿資料。
本來覺得:
喔~好像也還好嘛。
結果程式越寫越長之後,開始變成:
fetch("API網址")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
嗯……
一個 .then()。
兩個 .then()。
再一個 .catch()。
再繼續下去是不是要開始玩接龍???
所以今天來看看另一種寫法:
async / await
昨天的寫法是:
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
今天改成:
async function getUser() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
const data = await response.json();
console.log(data);
}
getUser();
欸?
看起來突然比較像:
第一步做完,再做第二步。
終於不用一直 .then().then().then() 了 XD
先看這行:
async function getUser() {
async 是在告訴 JavaScript:
這個 function 裡面會處理非同步的事情。
也就是像:
fetch()
這種不會馬上得到結果的操作。
所以如果要在 function 裡使用 await,
通常就要先幫 function 加上:
async
可以先簡單理解成:
先跟 JavaScript 報備一下:等等這裡要等人。
再來是:
const response = await fetch("API網址");
await 可以讓程式先等待這個 Promise 完成,
拿到結果之後,再繼續執行下面的程式。
所以:
const response = await fetch("API網址");
const data = await response.json();
看起來就很像:
先拿資料
↓
等資料回來
↓
轉成 JSON
↓
再繼續
這樣對我來說真的比較好讀。
不然昨天滿腦子都是:
這個 then 到底接的是上一個誰???
昨天 .then() 寫法有:
.catch()
那 async / await 通常可以搭配:
try...catch
例如:
async function getUser() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
const data = await response.json();
console.log(data);
} catch (error) {
console.log("出事了!", error);
}
}
getUser();
也就是:
try
→ 先試著做
catch
→ 出事我來接
很像:
你先去拿資料,出事再回來找我 XD
還是不能又全部躲在 Console。
HTML:
<h1 id="name">資料載入中...</h1>
JavaScript:
const name = document.querySelector("#name");
async function getUser() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
const data = await response.json();
name.textContent = data.name;
} catch (error) {
name.textContent = "資料讀取失敗 QQ";
}
}
getUser();
成功的話:
Leanne Graham
失敗的話:
資料讀取失敗 QQ
這樣至少不會 API 一掛掉,
網頁就直接站在那邊裝沒事 ==
原本:
fetch()
.then()
.then()
.catch();
也可以改成:
async function getData() {
try {
const response = await fetch("API網址");
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
兩種都可以處理非同步。
只是目前我自己看起來,
async / await 比較像正常的:
做完 A → 再做 B → 再做 C
比較不容易看到 .then() 看到眼神死 XD
昨天才剛認識 Promise,
今天就先學著不要被 Promise 嚇跑。
目前我先記:
async → 這個 function 裡會處理非同步
await → 等這件事情完成再繼續
try...catch → 出事的時候有人接
突然覺得 Fetch 好像沒有昨天那麼可怕了。
雖然我有預感,
JavaScript 一定還藏了一堆東西沒拿出來 ==
沒事。
一天挖一點。
Day 23,完成!