We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Await

The await keyword is used to wait for a Promise to resolve. Once it has been resolved, the await expression returns the value of the resolved promise. It's basically a more modern syntax for .then callbacks.

.then Callback

promise.then((message) => {
  console.log(`Resolved with ${message}`);
});

await Syntax

const message = await promise;
console.log(`Resolved with ${message}`);

Personally, I recommend using await over .then whenever possible. It's cleaner and easier to read.

Handling Rejections

When using await, if the promise is rejected, it will throw an error. That means we can use standard try/catch blocks to handle rejections.

try {
  const message = await promise;
  console.log(`Resolved with ${message}`);
} catch (error) {
  console.log(`Rejected with ${error}`);
}

Assignment

Similar to before, the updateMessageStatus function takes a message id, current status and delivered state and returns a Promise.

On line 1, call updateMessageStatus with inputs:

  • messageId = "M123"
  • currentStatus = "Sending"
  • isDelivered = true

Then on line 2, await the returned promise and save the resolved value in a variable called message which will be logged to the console (which is already written on line 5).

Tip

For extra difficulty, try combining lines 1 and 2 into one line by awaiting the output of updateMessageStatus.