Simplify your callback or Promise in Node.js application with async/await

0
95

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.

Node Async Await

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

What is Async/Await?

  • 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.

 

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.

Go into the project folder.

 

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

 

Install the nodemon server using the following command.

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

 

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

 

 

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.

 

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 !

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here