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:
-
loadUrl
funktsiyasiasync
bo’ladi. -
Hammasi
.then
ichiawait
bilan 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.
-
loadJson
dan chiqarilgan xato.catch
tomonidan hal qilinadi. Biz u yerdaawait loadJson(…)
dan foydalana olmaymiz, chunki bizasync
funktsiyasida emasmiz.