Await a JavaScript Promise in an async Function with the await Operator

InstructorMarius Schulz

Share this video with your friends

Send Tweet

The await operator is used to wait for a promise to settle. It pauses the execution of an async function until the promise is either fulfilled or rejected.

To learn more about async and await, check out my Asynchronous JavaScript with async/await course.

tsvika
~ 6 years ago

Amazing course!, Thank you very much! I was wondering what do you think about async/await vs generators and redux-saga?

Marius Schulzinstructor
~ 6 years ago

@gadi246: The right tool for the right job! async & await solve a different problem than redux-saga.

Sofiya Tepikin
~ 6 years ago

Thank you very much for this course. Really liked it. The only question I have is why in the end we can simply return response.json(). From the beginning I've understood that it is also an asynchronous function. Shouldn't we also await for it?

Marius Schulzinstructor
~ 6 years ago

@Sofia: Great question! You can do either return await response.json(); or return response.json(); in this case. The latter works because the return value of an async function is implicitly wrapped in a Promise, just as if you had manually wrapped Promise.resolve() around the return value.

In the case of return response.json();, we're passing a Promise to that Promise.resolve() call. This doesn't result in a nested Promise, though; instead, the returned Promise adopts the state of the response.json() Promise. We can therefore leave out the await in this specific case.

Note that in some cases, the behavior might be different if you await the Promise within the async function before returning it. If the Promise is rejected and the await expression is placed within a try/catch statement, the catch branch is executed. That wouldn't be the case if you returned the Promise directly:

async function queryAPI(endpoint) {
  const response = await fetch(API_URL + endpoint);
  if (response.ok) {
    try {
      return /* await */ response.json();
    } catch (e) {
      // If the response.json() method doesn't synchronously
      // throw an error, we won't enter this catch branch.
      // Uncomment the `await` operator above and we will!
      return Promise.reject(new Error("..."));
    }
  }
  throw Error("Unsuccessful response");
}

I hope this illustrates the difference!

Michael
~ 6 years ago

Very illuminating course. Really well-presented. Thank you.

Maria Charles
~ 3 years ago

Wow I learnt a ton... thanks

Erkan Buelbuel
~ 2 years ago

Excellent! Thanks very much! Unfortunately, the course ends where it starts to get interesting. The following topics are completely missing:

  • Creating Custom Asynchronous Iterators
  • Enhancing them with generators
  • Cancelling Pending Async Requests (User Cancellable Async Requests,..)