in , ,

Javascript async/await

Javascript async/await
Javascript async/await

In this tutorial, you will learn about JavaScript async/await keywords with the assistance of examples.

JavaScript Introduces catchphrases “async” and “await” as an addition to EcmaScript 2015.

There’s an extraordinary syntax to work with promises in a more comfortable design, called “async/await”. It’s shockingly straightforward and use.

You use the async catchphrase with a function to represent that the function is an asynchronous function. The async function returns a promise.

The syntax of async function is:

async function name(parameter1, parameter2, ...paramaterN) {
    // statements
}

Here,

  • name – the name of the function
  • parameters – parameters that are passed to the function

Example: Async Function

// async function example

async function f() {
    console.log('Async function.');
    return Promise.resolve(1);
}

f(); 

Output

Async function.

In the above program, the async catchphrase is used before the function to represent that the function is asynchronous.

Since this function returns a promise, you can use the chaining strategy then() like this:

async function f() {
    console.log('Async function.');
    return Promise.resolve(1);
}

f().then(function(result) {
    console.log(result)
});

Output

Async function
1

In the above program, the f() function is resolved and the then() method gets executed.


JavaScript await Keyword

The await catchphrase is used inside the async function to wait for the asynchronous activity.

The syntax to use await is:

let result = await promise;

The use of await stops the async work until the promise returns an outcome (resolve or reject) value. For instance,

// a promise
let promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
    resolve('Promise resolved')}, 4000); 
});

// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result = await promise; 

    console.log(result);
    console.log('hello');
}

// calling the async function
asyncFunc();

Output

Promise resolved
hello

In the above program, a Promise object is made and it gets resolved after 4000 milliseconds. Here, the asyncFunc() function is composed using the async function.

The await catchphrase waits that the promise will be finished (resolve or reject).

let result = await promise;

Consequently, hello is shown exclusively after the promise value is accessible to the outcome variable.

In the above program, if await isn’t used, hello is shown before Promise resolved.

Note: You can use await just within async functions.

The async work allows the asynchronous strategy to be executed in an apparently synchronous manner. In spite of the fact that the activity is asynchronous, it appears to be that the activity is executed in synchronous way.

This can be valuable if there are various promises in the program. For instance,

let promise1;
let promise2;
let promise3;

async function asyncFunc() {
    let result1 = await promise1;
    let result2 = await promise2;
    let result3 = await promise3;

    console.log(result1);
    console.log(result1);
    console.log(result1);
}

In the above program, await waits that each promise will be finished.


Error Handling

While using the async work, you compose the code in a synchronous way. Furthermore, you can likewise use the catch() technique to catch the error. For instance,

asyncFunc().catch(
    // catch error and do something
)

The other way you can deal with a mistake is by using try/catch block. For instance,

// a promise
let promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
    resolve('Promise resolved')}, 4000); 
});

// async function
async function asyncFunc() {
    try {
        // wait until the promise resolves 
        let result = await promise; 

        console.log(result);
    }   
    catch(error) {
        console.log(error);
    }
}

// calling the async function
asyncFunc(); // Promise resolved

In the above program, we have used try/catch block to deal with the blunders. In the event that the program runs effectively, it will go to the try block. Furthermore, if the program throws a blunder, it will go to the catch block.

To learn more about try/catch in detail, visit JavaScript JavaScript try/catch.


Benefits of Using async Function

  • The code is more readable than using a callback or a promise.
  • Error handling is simpler.
  • Debugging is easier.

Note: These two catchphrases async/await were presented in the more up to date form of JavaScript (ES8). Some older browsers may not support the use of async/await. To learn more, visit JavaScript async/await browser support.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

JavaScript Promise and promise Chaining

JavaScript Promise and promise Chaining

Javascript setInterval()

Javascript setInterval()