JavaScript Tutorial

Javascript Async/ Await

This is a special syntax to deal with promises in javascript, we call it syntactic sugar over Promises.

Async Function

When you mark a function as "async," it means that the function will have some asynchronous operations inside. These operations could be fetching data from a server, reading files, or doing any task that takes time.

Here, the name is the name of the function and the parameters is parameters that are passed to the function.

Input:-

Output:-

Await Keyword

Now, when you encounter an asynchronous task inside an async function, instead of using callbacks or promises, you can use the magical "await" keyword. It's like telling JavaScript, "Hey, I want to pause here and wait for this task to finish before moving on."

So, you can "await" the completion of an asynchronous task, and JavaScript will patiently pause the execution of your function until that task is done. It's like putting your function on hold and letting it resume when the awaited task is finished.

Here's the syntax to use await in async function:

let result = await promise;

Following example illustrate the use of await in promises.

Input:-

Output:-

But remember, you can only use "await" inside an async function. Think of async/await as a team that works together to handle asynchronous operations smoothly.

Why use Async/await when we already have Promises ?

The beauty of async/await is that it makes your code more readable and easier to understand. It saves you from the nested callback hell and avoids chaining promises all over the place. It brings a sense of order and makes asynchronous code look and behave more like synchronous code.

Go back to Previous Course