await Expressions Inside JavaScript async Functions

By Hemanta Sundaray on 2023-02-06

await expressions are a way to handle asynchronous operations in JavaScript. For example, if you're making an API request and you want to wait for the response before doing anything else, you can use await to wait for the response to come back.

Here's a simple example:

async function fetchData() {
  const response = await fetch("https://some-api.com/data")
  const data = await response.json()
  console.log(data)
}

In this example, we use await twice. First, we use it to wait for the response from the API, and then we use it again to wait for the JSON data to be parsed from the response.

const response = await fetch('https://some-api.com/data') is essentially saying: "Wait for the response from the API to come back, and when it does, store it in the response variable." Then, when you use await response.json(), it's saying: "Wait for the JSON data to be parsed from the response, and when it is, store it in the data variable."

Note that when you use await, the JavaScript engine pauses the execution of the function until the promise returned by the expression is resolved. If the promise is fulfilled (meaning it succeeded), then the value of the promise is returned. If the promise is rejected (meaning it failed), then an exception is thrown with the rejection value.

In our example, the fetch function returns a promise. We await that promise, so the function stops executing until the promise is resolved. Then, when the promise is resolved and the response is available, we use await again to wait for the JSON data to be parsed from the response.

Join the Newsletter