Node Async Await Example: The Complete Guide

0
477
Async-Await in Node.js example tutorial

ES 2017 introduced Asynchronous functions. Async functions are a cleaner way to work with asynchronous code in JavaScript. For example, you can simplify your callback or Promise-based Node.js application with async functions using async-await.

Async language constructs have been around in other languages, like async/await in C#, coroutines in Kotlin, and goroutines in Go. 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.

Async/Await in Node.js

  • 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 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 a 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 because their execution can be paused. The only fundamental difference is that they always yield a Promise instead of a  { value: any, done: boolean } object.

Now, let us take a simple example of Promise.

But before that, please check your Node.js version. My version is v9.8.0. So, I can use the async-await feature. If your Node.js has not had the latest version, 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);
});

The next step is to start the nodemon server using the following command.

nodemon server

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 the above code into the 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);

Node Async Await Example Tutorial

Async/Await in AJAX Request

To use the async/await method in Node.js AJAX request, use the node-fetch library. First, we need to install the node.js client-specific library to send an ajax request. We use the node-fetch library.

npm install node-fetch --save

We can use the async-await function like the following for the ajax request.

// server.js

const fetch = require('node-fetch');

async function asyncajaxawait(x)
{
  const res = await fetch('https://api.github.com/users/KrunalLathiya')
  const data = await res.json();
  console.log(data.name);
}

asyncajaxawait(10);

We have used the node-fetch library to send an ajax request to the Github API and get the response. It is the direct use of async-await. So, we have seen almost all use cases of an async-await feature. You can find more about async/await in this link. Finally, Node Async Await Example Tutorial is over. Thanks for taking it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.