Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
async
await

What is async/await in JavaScript?

Educative Answers Team

Promises were added in JavaScript to handle asynchronous operations easily. The async/await is syntactical sugar, added in ES7, that facilitates working with promises. Async/await helps with writing completely synchronous-looking code while performing asynchronous tasks.

await is used to wait for a promise to resolve or reject, and can only be used inside an asynchronous function.

Code

The code snippet below demonstrates the following scenario:

  1. A customer orders something.

  2. If it is an item on the menu, then the promise is resolved, and the order is handed over to the customer. Else, the promise is rejected.

  3. Next, the customer is asked for payment. Everything at this place costs 20 bucks. If the customer pays 20 or more, then the promise to make payment is resolved. Otherwise, it is rejected.

Note that the code waits for the promise to be resolved or rejected at the await statement. The execution only moves forward if the promise is resolved. The try-catch block is used to catch errors and unresolved promises:​

Console

RELATED TAGS

javascript
async
await
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring