Open In App

Async and Await in JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Async/await is a feature in JavaScript that allows you to work with asynchronous code in a more synchronous-like manner, making it easier to write and understand asynchronous code.

Async Functions always return a promise. Await Keyword is used only in Async Functions to wait for promise.

JS Async/Await is the extension of promises that we get as support in the language. In this article, we will be learning about async and await in JavaScript with examples.

Async Function

The Async function simply allows us to write promises-based code as if it were synchronous and it checks that we are not breaking the execution thread.

Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then JavaScript automatically wraps it in a promise which is resolved with its value.

Async Syntax

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

Async Function 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

Explanation

Here, an asynchronous function getData is declared using the arrow function syntax with the async keyword. Inside this function, a variable data is initialized with the string “Hello World”. Then, the function returns this data.

Await Keyword

Await is used to wait for the promise. It could be used within the async block only.

It makes the code wait until the promise returns a result.

Await Syntax

let value = await promise;

Await 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

Explanation

Here, an asynchronous function getData is defined using the arrow function syntax with the async keyword. Inside this function, there’s an await expression, which pauses the execution of the function until the promise is resolved. However, in this case, the awaited value is a string literal “Hello World”, which is not a promise, so it will be immediately resolved.

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.

Conclusion

We have covered the use of async and await in JavaScript. We learned how to use async/await syntax. Mastering async/await makes it easier to work with promises by removing the need for the .then() and .catch() methods.

Supported Browsers:

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

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 04 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads