async/await
async and await are two JavaScript keywords that make it possible to:
- initiate asynchronous requests (such as HTTP requests with
fetch) prefixed withawait - go back into the JavaScript event loop
- wait for and process other asynchronous events in the order that they occur
- resume execution of the line after
awaitas soon as the previousawaited request finishes
async function getData() {
const url = "https://someurl.com/data.json";
try {
const response = await fetch(url);
if(response.ok) {
const data = await response.json();
return data;
} else {
return Promise.reject(response);
}
} catch(e) {
return Promise.reject(e);
}
}
Call the function using Promise API:
getData().then(console.log).catch(console.error).finally(() => console.log("DONE"));
Or using async/await with IIFE:
(async function() {
try {
const result = await getData();
console.log(result);
} catch(e) {
console.error(e);
} finally {
console.log("DONE");
}
})();