Async and Await in JavaScript

Async and Await in JavaScript are powerful keywords used to handle asynchronous operations with promises. Async functions implicitly return promises, while Await pauses the execution until the promise is resolved. This simplifies asynchronous code and enhances readability by making it appear synchronous.

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(" w3wiki..");
        }, 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', ' w3wiki..' ]

Explanation:

  1. Promise Creation:
    • Two promises are created: one resolve immediately with “Hello”, and the other resolves after 1 second with ” w3wiki..”.
  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.

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 makes error handling straightforward.
  3. Avoids Callback Hell: Async and Await help in avoiding nested callbacks and complex promise chains.
  4. Better Debugging: Debugging async/await code is more intuitive as it behaves like 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: