The Wayback Machine - http://web.archive.org/web/20240930211304/https://www.geeksforgeeks.org/async-await-function-in-javascript/
Open In App

Async and Await in JavaScript

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Async and Await in JavaScript is used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows.

Async Function

The async function allows us to write promise-based code as if it were synchronous. This ensures that the execution thread is not blocked.

  • Promise Handling: Async functions always return a promise. If a value is returned that is not a promise, JavaScript automatically wraps it in a resolved promise.

Async Syntax

async function myFunction() {
  return "Hello";
}

Example: Here, we will see the basic use of async in JavaScript.

javascript
const getData = async () => {
    let data = "Hello World";
    return data;
}

getData().then(data => console.log(data));

Output
Hello World

Await Keyword

The await keyword is used to wait for a promise to resolve. It can only be used within an async block.

  • Execution Pause: Await makes the code wait until the promise returns a result, allowing for cleaner and more manageable asynchronous code.

Syntax

let value = await promise;

Example : This example shows the basic use of the await keyword in JavaScript.

javascript
const getData = async () => {
    let y = await "Hello World";
    console.log(y);
}

console.log(1);
getData();
console.log(2);

Output
1
2
Hello World

The async keyword transforms a regular JavaScript function into an asynchronous function, causing it to return a Promise.

The await keyword is used inside an async function to pause its execution and wait for a Promise to resolve before continuing.

Async/Await Example

Here, we will be implementing several promises in a method, and then that method we will use for displaying our result. You can check the JS async/await syntax in the example.

JavaScript
function asynchronous_operational_method() {
    let first_promise = 
        new Promise((resolve, reject) => resolve("Hello"));
    let second_promise = 
        new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(" GeeksforGeeks..");
        }, 1000);
    });
    let combined_promise = 
        Promise.all([first_promise, second_promise]);
    return combined_promise;
}

async function display() {
    let data = await asynchronous_operational_method();
    console.log(data);
}

display();

Output:

[ 'Hello', ' GeeksforGeeks..' ]

Explanation:

  1. Promise Creation:
    • Two promises are created: one resolve immediately with “Hello”, and the other resolves after 1 second with ” GeeksforGeeks..”.
  2. Combining Promises:
    • The Promise.all() method combines both promises into a single promise, combined_promise.
  3. Asynchronous Function:
    • The display() function is declared as async, indicating it contains asynchronous operations.
  4. Awaiting Promise Resolution:
    • The await keyword pauses execution until combined_promise is resolved.
  5. Logging Result:
    • The resolved array from combined_promise is logged to the console.

Note

To resolve and reject are predefined arguments by JavaScript.

  • resolve function is used when an asynchronous task is completed and returns the result.
  • reject function is used when an asynchronous task fails and returns reasons for failure.

Error Handling in Async/Await

JavaScript provides predefined arguments for handling promises: resolve and reject.

  • resolve: Used when an asynchronous task is completed successfully.
  • reject: Used when an asynchronous task fails, providing the reason for failure.

Example:

JavaScript
async function fetchData() {
  try {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

Advantages of Async and Await

  1. Improved Readability: Async and Await allow asynchronous code to be written in a synchronous style, making it easier to read and understand.
  2. Error Handling: Using try/catch blocks with async/await simplifies error handling.
  3. Avoids Callback Hell: Async and Await prevent nested callbacks and complex promise chains, making the code more linear and readable.
  4. Better Debugging: Debugging async/await code is more intuitive since it behaves similarly to synchronous code.

Conclusion

Async and Await in JavaScript have revolutionized asynchronous programming by making code more readable and maintainable. By allowing asynchronous code to be written in a synchronous style, they reduce the complexity associated with callbacks and promise chaining. Understanding and using async and await effectively can significantly enhance your JavaScript programming skills, making it easier to handle asynchronous operations in your projects.

Supported Browsers:

The browsers supported by the JS Async/Await Function are listed below:



Previous Article
Next Article

Similar Reads

Explain Promise.race() with async-await in JavaScript
In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the most commonly used promise methods that state whichev
3 min read
Explain Promise.any() with async-await in JavaScript
In this article, we will try to understand how to implement the Promise.any() method with async-await in JavaScript using some theoretical explanations followed by some coding examples as well. Let us firstly quickly understand the working of Promise.any() method with some theoretical examples (including the syntax of declaring this particular meth
4 min read
How to use await outside of an async function in JavaScript ?
In this article, we will try to understand in what way or by how we may use await outside of an async function in JavaScript with the help of both theoretical explanations as well as coding examples. Let us first understand the following shown section in which all the syntaxes of declaring a promise, executing a promise, and using async-await keywo
4 min read
Explain Promise.allSettled() with async-await in JavaScript
In this article, we will try to understand how we may implement the Promise.allSettled() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand about Promise.allSettled() method. This method is one of the most common methods available under the Promise obje
3 min read
How to use async/await with forEach loop in JavaScript ?
Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to traverse the array with the help of forEach loop.
2 min read
Explain Promise.all with async-await in JavaScript
In JavaScript, Promise.all with async-await is used to handle multiple asynchronous operations concurrently. By combining Promise.all with await, you can wait for all promises to resolve or any to reject, ensuring that all asynchronous tasks are complete before proceeding with the next code execution step. What is Promise.all()?Promise.all is a Jav
4 min read
How to delay a loop in JavaScript using async/await with Promise ?
In JavaScript, you can delay a loop by using async/await with Promise. By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread. What is async and await?async and await in JavaScript are used for handling as
2 min read
How does await and async works in ES6 ?
In this article, we will try to understand how exactly async and await works in ES6. Let us first try to understand what exactly async and await are along with their usage and then further we will see some examples in which we would see how we may use async and await along with the normal functions. Async and Await: Async and Await both are conside
3 min read
Compare Async/Await and Generators usage to Achieve Same Functionality
Asynchronous programming has become increasingly important in modern web development, as it allows for more efficient use of resources and can lead to better user experiences. Two popular approaches to asynchronous programming in JavaScript are async/await and generators. While both approaches have their own strengths and weaknesses, they can be us
6 min read
Difference between Promise and Async/Await in Node
Promises are used to handle the asynchronous operations with the help of .then() and .catch() chaining while async await acts as wrapper syntax for promise and provides more readable and synchronous-like syntax as try-catch for error handling. Asynchronous programming is fundamental in Node.js, ensuring non-blocking operations. Promises and async/a
4 min read
How to use Async-Await pattern in example in Node.js ?
Modern javascript brings with it the async-await feature which enables developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write. To use async-await, we just need to create an asyn
1 min read
Why is it possible to try-catch an async-await call ?
JavaScript's try-catch is used to handle errors and exceptions that occur when an error occurs during execution also called runtime error. The 'async' and 'await' are keywords in JavaScript that are used to write asynchronous code. The async keyword is used to declare an asynchronous function, which is a function that returns a promise and can be a
3 min read
Callbacks vs Promises vs Async/Await
Callbacks, Promises, and Async/Await are three different approaches in JavaScript for handling asynchronous operations. Let's briefly discuss each. CallbackCallbacks are functions passed as arguments to other functions, and they are executed after the completion of a specific task. Callbacks have been a traditional way of handling asynchronous oper
5 min read
How to use Async Await with Array.map in TypeScript ?
In this article, we will learn how we can use async wait with Array.map() method in TypeScript. In TypeScript, the async and await are mainly used to work with asynchronous tasks. Using this we can write the code that consists of the tasks that take time to complete like reading the file, fetching data from the server, etc. There are two approaches
3 min read
Explain Async Await with Promises in Node.js
Async/Await in Node.js is a powerful way to handle asynchronous operations. It allows you to write asynchronous code in a synchronous manner, making it easier to read, write, and debug. This feature is built on top of Promises, which represent a value that may be available now, or in the future, or never. To use async-await, we just need to create
4 min read
How to use Async/Await with a Promise in TypeScript ?
In TypeScript, you can use async and await with a Promise to simplify asynchronous code and make it more readable. What is a Promise?A promise in TypeScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that may be available now, in the future, or never. Syntax:const
3 min read
How to convert an onload promise into Async/Await ?
In this article, we will learn how to unload promise into Async/Await with multiple approaches. An onload promise is a promise that is resolved when any onload event is fired onto a DOM ( Document Object Model ) element. The onload event is fired when the element has finished loading all of its resources, such as images and scripts. It's like a com
3 min read
How to Rewrite promise-based applications to Async/Await in Node.js ?
In this article, we are going to see how we can rewrite the promise-based Node.js application to Async/Await. Suppose we have to read the content of a file 'index.txt', and we have a function 'readFilePromise' which uses the 'readFile' method of the fs module to read the data of a file, and the'readFilePromise' function resolves the promise if the
2 min read
Async Await in Node.js
Async and await in Node are the modern way of handling asynchronous operations more efficiently. These are powerful keywords that replaces the traditional callback and Promise chaining approaches. Handling Asynchronous Operations Before Async AwaitCallbacksBefore Node version 7.6, the callbacks were the only official way provided by Node to run one
3 min read
What is the difference between async.waterfall and async.series?
async.waterfall: This waterfall method runs all the functions(i.e. tasks) one by one and passes the result of the first function to the second, second function's result to the third, and so on. When one function passes the error to its own callback, then the next functions are not executed. So, the main callback is immediately called with the error
3 min read
What is the difference between await and yield keywords in JavaScript ?
In this article, we will see how Await keyword is different from Yield keywords. Generator Functions: Functions that can return multiple values at different time interval as per the user demands, and can manage its internal state are generator functions. A function becomes a Generator function if it uses the function* syntax. They are different fro
3 min read
How to set Maximum Execution Time for a Promise Await in JavaScript ?
In JavaScript, asynchronous operations are more common, often implemented using promises and async/await syntax. However, there are certain scenarios where we want to set the execution times for these asynchronous operations to prevent them from running indefinitely. In this article, we'll explore various ways to set the maximum execution time for
3 min read
Handling Promise rejection with catch while using await
In this article, we will try to understand how we may handle Promise's rejection with a try/catch block while using await inside an asynchronous (having prefix as an async keyword) function (or a method). Syntax: Let us first quickly visualize the following illustrated syntax which we may use to create a Promise in JavaScript: let new_promise = new
2 min read
How to fetch data from APIs using Asynchronous await in ReactJS ?
Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. PrerequisitesReact JSFetch data from APIApproachTo fetch data from APIs using Asynchronous await in
3 min read
Await Component in React Router
The <Await> component in React Router v6 is designed to handle the rendering of deferred values with automatic error handling. It is especially useful when dealing with asynchronous data fetching in components rendered by React Router routes. The <Await> component ensures that the rendering of components is deferred until the required d
5 min read
Remix Components: Await
The Await component in Remix simplifies handling the asynchronous data by managing loading, success, and error states. It enhances performance and user experience in modern React applications. Avait Component in RemixThe Await component in Remix is a powerful tool used to handle asynchronous operations within your application's components. It allow
7 min read
Understanding the Async in JavaScript
Definition: Async is a short form for “asynchronous”. Synchronous means executing statements one after the other which implies the next statement will get executed only after the previous statement is executed completely. Whereas in Asynchronous calls the next statement gets executed without even waiting for the previous one's execution. JavaScript
4 min read
How to access object properties from result returned by async() function in JavaScript ?
In this article, we will see how to access the properties of a javascript object result returned by the async() function in Javascript. A javascript object property is a variable that is associated (read attached) with the object itself, i.e. the properties have a name and value is one of the attributes linked with the property, which defines the a
3 min read
How to throw an error in an async generator function in JavaScript ?
In this article, we will try to understand how to throw an error in a synchronous (abbreviated as "async") generator function in JavaScript with the help of theoretical as well as coding examples. Let us first have a look into the following section which will show us the syntax for declaring an async generator function. Syntax: async function* func
2 min read
What is the use of the async function in JavaScript?
The use of async functions in JavaScript is to simplify writing asynchronous code by using the async keyword. Async functions allow you to write asynchronous code in a synchronous-like manner, making it easier to manage and understand asynchronous operations. Example: Here, fetchData() is an async function that fetches data from an API asynchronous
1 min read