AppDividend
Latest Code Tutorials

Node Async Await Example Tutorial

2,023

Get real time updates directly on you device, subscribe now.

Node Async Await Example Tutorial is today’s leading topic. ES 2017 introduced Asynchronous functions. Async functions are essentially a cleaner way to work with asynchronous code in JavaScript. Using async-await, you can simplify your callback or Promise based Node.js application with async functions.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

# Node Async Await Example Tutorial

Async language constructs have been around in other languages for a while, 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.

#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 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 in the sense that 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 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

So, here after 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);

 

Node Async Await Example Tutorial

#Async/Await in AJAX Request.

First, we need to install the node.js client specific library to send an ajax request. We use the node-fetch library.

Related Posts
1 of 17
npm install node-fetch --save

For the ajax request, we can use the async-await function like the following.

// 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);

Here, we have used the node-fetch library to send an ajax request to the Github API and get the response. It is the direct and straightforward use of async-await. So, we have seen the 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.

Leave A Reply

Your email address will not be published.

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