fbpx

Simplify your callback or Promise with async await in Nodejs application

Async Await Nodejs

With the release of Node.js version 8, the long-awaited async functions have landed in Node.js as well. Before we understand the asyn await in Node.js, let us dive into what and why we use async await in the first place.

If you really want to get rid of callback hell OR chained promises, then it’s time to remove those code snippets from your codebase. We will see below step by step.

What is Async Await in Nodejs ?

  • It is the newest way to write asynchronous code in JavaScript.
  • It is non-blocking (just like callbacks and promises).
  • Async/Await is created to simplify the process of working with and writing chained promises.
  • An async function returns the Promise. If the function throws an error, the Promise will be automatically rejected, and if the function returns the value that means the Promise will be resolved.

Syntax of Async Function

We need to add the async keyword before a function.

// Normal Function
function add(a,b){
  return a + b;
}
// Async Function
async function add(a,b){
  return a + b;
}

Async function declarations return an async object. These are similar to Generator in the sense that their execution can be paused. The only fundamental difference is that they always create a Promise instead of an object.

Now, let us take a simple example of Promise.

But before that, please check your Node.js version. If your Node.js has not the latest version, then please update to the newest version.

Now, create a project folder.

mkdir node-examples

Go into the project folder.

cd node-examples

Now, create a package.json file using the following command.

npm init -y

Install the nodemon server using the following command.

npm install nodemon --save

Create a new file called server.js inside the root. Write the following code inside it.

// server.js

function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}

square(10).then(data => {
  console.log(data);
});

Next step is to start the nodemon server using the following command.

 

nodemon server.js

So, hereafter two seconds, we can see the square of 10. Function square returns the promise, and after resolving that promise, we get our squared data.

Switching from Promises to Async/Await.

Okay, now turn above code into async/await function.

// server.js

function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}

async function layer(x)
{
  const value = await square(x);
  console.log(value);
}

layer(10);

Output:

The great thing about having our function in Promise form is that we don’t actually need to “make it an async/await version” if we don’t want to. When we call/execute the function, we can simply use the async/await keywords.

Please Comment if You Want some More examples or You are stuck at any place .We will be happy to help you ! Thanks !