JavaScript async / await

Subject: JavaScript

async and await are modern JavaScript features introduced in ES2017 (ES8) that simplify writing asynchronous code. They work on top of Promises and make asynchronous code look and behave like synchronous code, improving readability and debugging.


What is async?

An async function always returns a Promise. The await keyword can only be used inside async functions.

Syntax:


What is await?

The await keyword pauses the execution of an async function until the Promise is resolved or rejected.

Syntax:


Example: Basic Usage

Output:


Why Use async / await?

  • Cleaner and more readable than .then() chains.
  • Easier to write sequential async logic.
  • Works well with try...catch for error handling.

Example: Error Handling with try...catch


Example: Multiple Await Statements

Each await waits for the previous operation to complete.


Parallel Execution with Promise.all()

To run asynchronous tasks in parallel:


Mixing with Non-Async Functions

You can call async functions from regular functions, but use .then() or await from another async function:


Key Takeaways

  • async functions return a Promise.
  • await pauses the function until the Promise is resolved.
  • Use try...catch for error handling.
  • Great for writing cleaner, sequential asynchronous code.
  • Use Promise.all() for parallel execution.
Next : Callback Function