Async/await yordamida qayta yozing
Va'dalar zanjiri bobidagi misollardan birini .then/catch o’rniga async/await yordamida qayta yozing:
function loadJson(url) {
return fetch(url).then((response) => {
if (response.status == 200) {
return response.json();
} else {
throw new Error(response.status);
}
});
}
loadJson("no-such-user.json").catch(alert); // Error: 404
Izohlar kod ostida:
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("no-such-user.json").catch(alert); // Error: 404 (4)
Izohlar:
-
loadUrlfunktsiyasiasyncbo’ladi. -
Hammasi
.thenichiawaitbilan almashtiriladi. -
Buni kutish o’rniga
response.json()ni qaytarishimiz mumkin, masalan:if (response.status == 200) { return response.json(); // (3) }Shunda tashqi kod ushbu va’dani hal qilishini kutishi kerak edi. Bizning holatda bu muhim emas.
-
loadJsondan chiqarilgan xato.catchtomonidan hal qilinadi. Biz u yerdaawait loadJson(…)dan foydalana olmaymiz, chunki bizasyncfunktsiyasida emasmiz.