Node/Javascript Async/Await/Promise Function to Fetch JSON of an API URL


Most APIs return JSON.

Below is a simple example of a Node.js (Javascript) async function that uses the node-fetch package to fetch JSON data from the provided URL.

Firstly, you’ll need to install the node-fetch package if you haven’t already:

1
npm install node-fetch
npm install node-fetch

Next, you can use the following function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const fetch = require('node-fetch');
 
async function fetchJSONData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const jsonData = await response.json();
        return jsonData;
    } catch (error) {
        console.error('There was a problem fetching the data:', error.message);
    }
}
const fetch = require('node-fetch');

async function fetchJSONData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const jsonData = await response.json();
        return jsonData;
    } catch (error) {
        console.error('There was a problem fetching the data:', error.message);
    }
}

An example usage:

1
2
3
4
5
6
// Test the function
(async () => {
    const url = "https://sds1.steemworld.org/accounts_api/getAccount/justyy";
    const data = await fetchJSONData(url);
    console.log(data);
})();
// Test the function
(async () => {
    const url = "https://sds1.steemworld.org/accounts_api/getAccount/justyy";
    const data = await fetchJSONData(url);
    console.log(data);
})();

This function will make an asynchronous request to the given URL and then parse the result as JSON. If there are any errors (e.g., if the request fails, or if the response isn’t valid JSON), the function will catch those and print an error message to the console.

The async function inherently returns a promise, but if you want it to be more explicit, you can wrap the fetch operation within a new Promise. Here’s how you can do that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const fetch = require('node-fetch');
 
function fetchJSONData(url) {
    return new Promise(async (resolve, reject) => {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                reject(`HTTP error! Status: ${response.status}`);
            } else {
                const jsonData = await response.json();
                resolve(jsonData);
            }
        } catch (error) {
            reject('There was a problem fetching the data:', error.message);
        }
    });
}
const fetch = require('node-fetch');

function fetchJSONData(url) {
    return new Promise(async (resolve, reject) => {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                reject(`HTTP error! Status: ${response.status}`);
            } else {
                const jsonData = await response.json();
                resolve(jsonData);
            }
        } catch (error) {
            reject('There was a problem fetching the data:', error.message);
        }
    });
}

And here is how we use it:

1
2
3
4
5
6
7
8
// Test the function
fetchJSONData("https://sds1.steemworld.org/accounts_api/getAccount/justyy")
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });
// Test the function
fetchJSONData("https://sds1.steemworld.org/accounts_api/getAccount/justyy")
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });

Now, fetchJSONData explicitly returns a promise that either resolves with the JSON data or rejects with an error message.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
450 words
Last Post: How to Implement a Reversed Iterator in Python?
Next Post: Teaching Kids Programming - Two Algorithms to Find All Numbers Disappeared in an Array (Hash Set)

The Permanent URL is: Node/Javascript Async/Await/Promise Function to Fetch JSON of an API URL

Leave a Reply