async/await

async and await are two JavaScript keywords that make it possible to:

  1. initiate asynchronous requests (such as HTTP requests with fetch) prefixed with await
  2. go back into the JavaScript event loop
  3. wait for and process other asynchronous events in the order that they occur
  4. resume execution of the line after await as soon as the previous awaited 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");
  }
})();

References:
  1. MDN: Fetch API