Quantcast
Channel: Sankarsan's Journal
Viewing all articles
Browse latest Browse all 42

Async/Await in Node.js/JavaScript–Part1

$
0
0

In the previous few posts we have discussed on Promise in JavaScript and how it helps to solve the issues related to callbacks resulting in more readable and maintainable code.In this post we will discuss on the async and await keywords which are nothing but a syntactic sugar coat on Promise leading to a more streamlined and maintainable code.

The async functions are declared with the async keyword and await keyword is permitted within the async functions.

The async functions always returns a Promise object which will be:

  • Resolved with the value returned by async function
  • Rejected with the exception thrown by the async function.

We have defined a very simple async function below which returns the square of its input.

image

This function will return a Promise which will resolve with a square of its input value and will be rejected if the input value is negative.

image

The above program will have the following output:

image

If we pass a negative value then the Promise will be rejected as shown below.

image

image

So this async function is quite similar to the following:

image

Note, that using the async keyword will simplify the above code to a great extent.

The await keyword is permitted only within an async function and is used to wait on an Promise or any other value. If it’s waiting on an Promise the return value will be the fulfilled value of a Promise or any other value.

We have created a promisified version of the squared function as shown below.

image

We will now use await keyword and invoke this from an async function as shown below:

image

This code will print the following clearly indicating that await call is waiting about 1 sec for the Promise to get resolved.

image

If we invoke this with a negative value it will have the following output:

image

image

This is because await keyword throws the rejected value of the Promise which should be handled properly as shown below:

image


    Viewing all articles
    Browse latest Browse all 42

    Trending Articles