Asynchronous fetching in TypeScript


Objectives

Learn how to use fetch with async/await in TypeScript

Async/Await

To use it in a Node.js environment, you need to use a library like node-fetch or axios to make HTTP requests.

node-fetch

axios

The axios library is used to make an asynchronous GET request to the specified API URL. The response data is extracted from the response object, and you can further process it within the .then block. If any errors occur during the request, they will be caught and logged in the .catch block.

Demo: Fetching Local Business Data using Rapid API

First, I import the Axios library, which is used to make HTTP requests. Then, two interfaces, "Response" and "Business," are defined to specify the structure of the data returned from the API.

The main function "getBusinesses" is responsible for fetching the business data. It sets up the necessary parameters for the API request, including the request method, URL, query parameters (such as the search query, limit, latitude, longitude, language, and region), and headers (including the API key and host).

Using Axios, a GET request is made to the specified URL with the provided options. The response is handled asynchronously as a promise.

Once the response is received, the data property from the response, which conforms to the "Response" interface, is extracted. This data property contains an array of businesses. The code then maps over this array to transform each business object, selecting specific properties such as name, phone number, rating, review count, and timezone. These transformed objects are stored in a new array called "allBusinesses."

Finally, the "allBusinesses" array is logged to the console, providing information about each business, such as its name, phone number, rating, review count, and timezone. In case of any errors during the API request, the code catches them and logs them to the console.

To initiate the API request and retrieve the business data, the "getBusinesses" function is called. The expected output, provided as a comment, demonstrates a sample list of businesses in San Francisco, USA, along with their respective details.

Let's see the final code

Tags

TypeScript JSONplaceholder Rapid API

This post is also on Medium

Source