POST Request with Async/Await

There is a term used for async/await called Syntactic Sugar. Async/Await are also built on top of Promises. Because it provides a much cleaner and easy-to-use syntax with normal javascript function to make an API call they are named as syntactic sugar.


Let's see how it uses a javascript function to make asynchronous calls and return promises.

async function getCountriesList() {
  try {
    let response = await fetch("https://restcountries.com/v3.1/all");
    let data = await response.json();
    console.log("Response Data: ", data);
  } catch(error) {
    console.error("Error: ", error);
  }
}
getCountriesList();


As you can see, the more you explore different methods the more easy it is to make an API call. The above example uses async the keyword at the beginning of the function to mark this function as asynchronous, while making a request and waiting for the server response we use await the keyword. Also, I have wrapped the whole example in try/catch a block to get more control over the code and Error messages.