Rewrite using async/await
Rewrite the one of examples from the chapter Promise Zinciri using async/await
instead of .then/catch
:
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') // (3)
.catch(alert); // Error: 404
The notes are below the code:
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)
Notes:
-
The function
loadJson
becomesasync
. -
All
.then
inside are replaced withawait
. -
We can
return response.json()
instead of awaiting for it, like this:if (response.status == 200) { return response.json(); // (3) }
Then the outer code would have to
await
for that promise to resolve. In our case it doesn’t matter. -
The error thrown from
loadJson
is handled by.catch
. We can’t useawait loadJson(…)
there, because we’re not in anasync
function.