Skip to main content

03.01 JS Node. Make parallel HTTP requests

You can make parallel HTTP requests using JS node.

/*
* This code is structured to handle multiple HTTP GET requests concurrently,
* using axios to perform the requests and Promise.all to manage them simultaneously.
*/

// Importing the axios library for making HTTP requests
import axios from "axios";

export default async function run({ execution_id, input, data }) {
// Defining an array of URLs to make HTTP requests to
const urls = ['https://dummyjson.com/carts', 'https://dummyjson.com/users', 'https://dummyjson.com/quotes'];

try {
// Using Promise.all to perform simultaneous HTTP requests to the URLs defined above
// The map function applies 'httpRequest' to each URL in the 'urls' array
const results = await Promise.all(urls.map(url => httpRequest(url)));

// Returning the results of the HTTP requests
// This is where you can handle the results as needed in your application
return {
res: results
};
} catch (error) {
// Logging any errors to the console
console.error(error);
// Rethrowing the error to be handled by the caller of this function
throw error;
}

// Defining an asynchronous function 'httpRequest' to handle individual HTTP requests
async function httpRequest(rawURL) {
try {
// Making a GET request to the provided URL using axios
const response = await axios({
method: "GET",
url: rawURL
});
// Returning the data part of the response
// This can be modified according to the needs of the application
return response.data;
} catch (error) {
// Logging any errors encountered during the HTTP request
console.error(error);
// Rethrowing the error to be handled by the caller of 'httpRequest'
throw error;
}
}
}