Promises and Async Await (Javascript)

Promises and async/await are a way to handle asynchronous actions in Javascript.

Promises

const getDataFromAPI = () => {
  // do stuff
  return fetch('url')
};

function main () {
  let apiData;
  getDataFromAPI()
    .then(data => apiData = data)
    .catch(error => console.error(error));

  if (apiData) {
    // do stuff
  }
}

Async/Await

const getDataFromAPI = () => {
  // do stuff
  return fetch('url')
    .then(data => apiData = data)
    .catch(error => console.error(error));
};

async function main () {
  let apiData;
  try {
    apiData = await getDataFromAPI();
  } catch (error) {
    console.error(error);
  }

  if (apiData) {
    // do stuff
  }
}

References

Last modified: 202108112348