javascript

Async/Await in Javscript

Async/Await in Javscript

In this tutorial, we will learn about how to use Async/Await in JavaScript.

Since ES 2017, there is now an even better and easier way to consume premises, which is called async-await.

Async/Await makes it easier to write promises. The keyword ‘async’ before a function makes the function return a promise, always. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.

Inside an async function, we can have one or more await statements, await will stop the code execution at this point of the function until the promise is fulfilled.

Here, you might think isn't stopping the code, blocking the execution?

the answer is actually no, in this case, because stopping execution in an  async function,

which is what we have here is actually not a problem because this function is running asynchronously in the background and so therefore it is not blocking the main threat of

execution, So it's not blocking the call stack

So it's the fact that it makes our code look like regular synchronous code while behind the scenes, Everything is in fact asynchronous.

Anyway, as soon as this promise here is resolved, then the value of this whole await expression that we have here is going to be the resolved value of the promise and so we can simply store that into a variable.

basically, await is in fact, simply syntactic sugar over the then method in premises.

So of course behind the scenes, we are still using premises but We are simply using a different way of consuming them here

Example :

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

// using created promise with 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

While using the async function, we can also use the catch() method to catch the error as shown in the above example.

Conclusion:

Thanks for reading. in this post, we have covered some basic introduction of node js so, its good to have some basic knowledge of node.js before we dive into some advanced topic.

Do let me know If you face any difficulties please feel free to comment below we love to help you. if you have any feedback suggestions then please inform us by commenting.

Don’t forget to share this tutorial with your friends on Facebook and Twitter.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment