Node Fetch API Send HTTP Request with Async Await Tutorial

Asynchronous programming is better when it comes to the performance and responsiveness of the application. But do you know how to write asynchronous code in Node js?

Well, if you don’t know, then don’t worry, we are here to help you.

Today, In this short tutorial, you will learn how to create an asynchronous function that handles the HTTP GET request using JavaScript’s async and await keywords.

To give you the complete idea, we will create a simple node app from absolute scratch. We will then use the country details REST API and take the asynchronous approach to make the HTTP Get request to fetch the country data or information.

To send the request to the server, we will use the async function and await operator. The async and await return the Promise response asynchronously. By following this approach, we will learn to communicate with the server in the node.

Before we go further, we would like to tell you other options to help you achieve the same with less difficulty. Nevertheless, our aim is to make you familiar with every possibility to enhance your knowledge about JavaScript and modern JavaScript-based frameworks.

Let us understand what the asynchronous means in the programming world.

There are two types of approaches; synchronous and asynchronous.

Synchronous means you can perform a single operation simultaneously; it has certain limitations. That means you cannot execute multiple functions at once. Let’s assume you have a series of functional programs connected to every program.

If somehow any function throws an error or still processing, then, in that case, the subsequent function won’t work.

An asynchronous approach is used to deal with that problem, and you can execute multiple functions simultaneously.

As a developer, we heavily rely on the data that comes from another source.

Usually, when we request the server, it returns a response. From request making to receiving a response takes some time, and in this situation, we take the asynchronous approach.

There are couple of ways to create asynchronous requests.

You can either use the callback function or the The Promise object.

The Promise object is handy when it comes to async programming. It takes resolve and reject parameters and returns a response when the Promise is fulfilled. Later you can retrieve the resolve and reject response using then and catch block.

You can initialize a Promise object using new Promise (resolve, reject) object.

Let’s get started.

How to Handle HTTP Requests Asynchronously with Async / Await in Node Js

  • Step 1: Build Project Folder
  • Step 2: Set Up Package JSON
  • Step 3: Make Server File
  • Step 4: Configure Fetch API in Node
  • Step 5: Make Asynchronous Request
  • Step 6: Get Async and Await Response

Build Project Folder

We have to create a new project folder, so open the command prompt and run the following command.

mkdir node-fetch

Head over to the project’a root:

cd node-fetch

Set Up Package JSON

Next, we have to type and execute the given command.

This command will generate a package.json file that beholds your node project’s information.

npm init

Make Server File

Next, you need to create a server.js file. Now, you require to register the server.js file in scripts property.

Go to package.json file and add the script as suggested below.

  "scripts": {
    "start": "node server.js"
  },

Configure Fetch API in Node

Fetch API is not included in Node; you must configure it manually.

You can run the following command from the console, and it will install the Fetch API module in Node js application.

npm install node-fetch

Open the package.json file, add the “type”: “module” just above the scripts property.

{

  "type": "module",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    ...
    ...    
    "node-fetch": "^3.1.0",
    ...
    ...    
  }
}

Make Asynchronous Request

In this Node Async Await example, we will go one step beyond and use the latest async function and await operator to handle the asynchronous request.

It is not wrong to say async/await is the higher or better manifestation of Promise object.

import fetch from 'node-fetch'

const API = 'https://restcountries.com/v3.1/all'

const getCountryData = async () => {
  let response = await fetch(API)

  if (response.status === 200) {
    return await response.json()
  } else {
    throw new Error('Something bad happened :(')
  }
}

getCountryData()
  .then((res) => {
    console.log(res)
  })
  .catch((error) => {
    console.log(error.message)
  })

Get Async and Await Response

Now, you are entirely ready to view the response in the terminal. Make sure to run the node program using the given command.

node server.js

After executing the command the country data appears on your terminal.

Summary

Node Fetch API Send HTTP Request with Async Await Tutorial

In this tutorial, we learned how to configure the Fetch module in Node js, how to use async and await keywords to build an asynchronous program regarding server communication.

The async and await provide a better way to make asynchronous requests in JavaScript-based applications.

The async keyword is defined right before the function, and it makes the function asynchronous by adding the Promise object. A function defined with the async keyword returns a Promise response.

On the other hand, the await keyword is used inside the async function; its primary job is to wait for the Promise to be fulfilled.

It pauses the function’s execution until the Promise returns the response; after the Promise is fulfilled, it incorporates the Promise values and resumes the Promise execution.

There are a few things that you must know about await:

Await offers simpler and easier way to write asynchronous code.

Always remember that await can’t be used with regular functions.

You can define multiple await operators within a single async function that saves us from creating promise chaining.