使用 async/await 重寫
使用 async/await
取代 .then/catch
,重寫章節 Promise 串接 中的範例程式碼
function loadJson(url) {
return fetch(url)
.then(response => {
if (response.status == 200) {
return response.json();
} else {
throw new Error(response.status);
}
});
}
loadJson('https://javascriptinfo.dev.org.tw/no-such-user.json')
.catch(alert); // Error: 404
註解在程式碼下方
async function loadJson(url) { // (1)
let response = await fetch(url); // (2)
if (response.status == 200) {
let json = await response.json(); // (3)
return json;
}
throw new Error(response.status);
}
loadJson('https://javascriptinfo.dev.org.tw/no-such-user.json')
.catch(alert); // Error: 404 (4)
註解
-
函式
loadJson
變成async
。 -
所有內部的
.then
都以await
取代。 -
我們可以
return response.json()
,而不必等待它,如下所示if (response.status == 200) { return response.json(); // (3) }
然後外部程式碼必須
await
該承諾才能解決。在我們的案例中,這並不重要。 -
從
loadJson
拋出的錯誤由.catch
處理。我們無法在那裡使用await loadJson(…)
,因為我們不在async
函數中。