Iterate over an array using JavaScript and send a request to an API endpoint for each element in the

What is the most efficient JavaScript loop to use for this scenario?

I need to make API calls for each value in the array, which could potentially contain more values than what's shown below. After researching different types of loops and Promise.all, I'm unsure which approach to take. Example

//    API Call 1. ABC
//    API Call 2. DEF
//    API Call 3. GHI
//    API Call ....

// Input format example [ABC, DEF, GHI, ... ...]
    
    var alp = "ABC, DEF, GHI";
    var letters = alp.split(',');
    var array = [letters];

    
    // API Request
    
    var apiRequest = http.request({
        'endpoint': 'site',
        'path':'/api/test/table/records', 
        'method': 'POST',
        "headers": {
        "Authorization": "Basic xxxxxxxxxxx=",
        "Content-Type": "application/json"
    
        }
    
    });
    
    
    var data = {};
    
    var dept = {};
    
    // Switch naming
    
    switch (letters[0]) {
    
        case 'ABC':
            site = "A B.C";
            break;
        case 'DEF':
            site = "D E.F";
            break;
        case 'GHI':
            site = "G H.I";
            break;
    }
    
    var u_department = dept;
    data.u_department = u_department;
    
    var apiResponse = apiRequest.write(data);

Where should I insert this code block?

var data = {};
var site = {};

   switch (letters[0]) {
    
        case 'ABC':
            site = "A B.C";
            break;
        case 'DEF':
            site = "D E.F";
            break;
        case 'GHI':
            site = "G H.I";
            break;
    }
var u_department = site;
data.u_department = u_department;
var apiResponse = apiRequest.write(data);

Answer №1

To implement a simple and effective solution, you can utilize a for loop to store each promise in an array. After the loop completes, you can then use Promise.all(promiseArray) to handle actions based on resolved or rejected promises.

let promiseArray = [];
for(let i=0;i<data.length;i++){
   var apiRequest = http.request({
       ....
     }
    });
   promiseArray.push(apiRequest)
}

Promise.all(promiseArray)
.then(fn)
.catch(fn)

More information about Promise.all([]) can be found here

Learn more about Promise.all()

Here is a brief example using JSONPlaceholder APIs

const todos = [1,2,3,4,5];
let promiseArray = [];
for(let i=0;i<todos.length;i++){
 promiseArray.push(fetch('https://jsonplaceholder.typicode.com/todos/'+todos[i]))
}

Promise.all(promiseArray)
.then(values=>values.map(value=>console.log(value.url+" ==> "+value.status)))
.catch(err=>console.log(err))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...

Keep your Vue table continuously updated in real-time

While I have come across similar questions like this and this, my issue presents a unique challenge. I am polling data for a table every second from my REST Api using axios. Despite this, I want the user to be able to freely manipulate (e.g. order, sort, ...

What is the process for accessing the inherent color of an STL file with the help of three.js?

I have a binary STL file that is colored. I can easily view the colors using an online mesh viewer, which you can find at . Despite successfully loading and visualizing the STL file using my standard approach below, the intrinsic colors do not display cor ...

In Android, parsing a JSON array consistently returns null values

How can I properly parse this JSON array? {"1": {"0":"3","id_disc":"3","1":"Research and design of computer systems","name":"Research and design of computer systems","2":"RDCS ","s_name":"RDCS "} ,"2": {"0":"5","id_disc":"5","1":"Civil defense and labor p ...

retrieving JSON data using ajax and processing it in PHP

I have some data that needs to be sent to the backend, and it looks like this: function view(){ let id = "12345678"; let profile = [{name:"dave", department : "Engineering"}, {name:"Tedd", ...

Ways to adjust the border color when error helper text is displayed on a TextField

I am currently working with React Material UI's TextField element. What I aim to achieve is when the submit button is pressed, the helpertext displayed should be "Please enter the password." It should look like this: https://i.sstatic.net/Nu0ua.png ...

Contrast the specific format of a String in Java with the general

I am interested in developing Java code that can determine whether a given function fits into specific predefined forms. The forms I am looking for are bcos(fx), bsin(fx), and btan(fx) where both 'b' and 'f' are integers. For example, ...

What is the proper method to refresh a single component from another in Vue.js?

Recently, I encountered the following scenario with a select element: <select @change="getValuesFromDate($event)"> <option value="1">Last 24 hours</option> <option v ...

Exploring the Plaid QuickStart demo in JavaScript

I'm encountering an issue while trying to implement Plaid functionality in a JavaScript environment. Despite following the documentation, I am unable to get it to function as expected. Initially, I create a link token using Node.js with the following ...

Using JQuery's $.ajax() method to send a post request and pass data to invoke a specific method in

I'm currently in the process of learning JQuery and encountering some challenges with utilizing the $.ajax() function. My goal is to send data to a controller for processing. During my debugging of the JQuery, it seems that the ajax call isn't b ...

Node.js: Exploring the Differences Between Synchronous and Asynchronous Code

Currently, my team is delving into the world of node for an internal project and to gain a deeper understanding of how to utilize this technology effectively. As individuals without a specific asynchronous background, we are facing some challenges with th ...

Is there a way for me to make a local HTML page save text directly to a file on my computer?

Currently, I am working on a straightforward HTML+JavaScript application that is designed to be loaded from a local file and run within the user's browser. The main functionality of this app will be to enable users to input text into a textarea and sa ...

How can you organize a 2D array in C++ through the use of built-in functions or alternative techniques?

I currently have a 2D array as shown below. ( array[5][2] ) 20 11 10 20 39 14 29 15 22 23 Once sorted, the array should appear like this. 10 20 20 11 22 23 29 15 39 14 This sorting is based on comparing values in the first column only. I ...

Error: Unable to iterate through events using forEach method in Leaflet and VueJS due to TypeError

I am currently working on a Vue project and I want to incorporate Leaflet maps within my components. The map is displaying correctly, but I encounter an error when attempting to add a marker to the map. The specific error message that I receive is: Un ...

Arranging multiple selections in Dojo's dijit

Just wondering if there's a built-in way in Dojo/Dijit multiselect to sort the options, or do I have to manually implement it? Many thanks Edit: I managed to solve my issue by implementing a sorting algorithm. Here's the code for anyone who mi ...

The connection between IE11 and Google is not functioning properly

Currently, I am working on an IE11 extension, which involves using an XMLHttpRequest (GET) to retrieve data from Google's settings page. The code is executed on the extension's background page. Here are the specific details I am including in the ...

The issue I'm facing in Jest is the "SyntaxError: Unexpected token 'export'" even after configuring transformIgnorePatterns

When executing npm run test, which triggers the execution of jest, a test suite fails with the following error message: /home/anthony/nosync/development/openmeteo/enhydris-web-frontend/node_modules/vue-notifications/dist/vue-notifications.js:130 export def ...

Display a block by using the focus() method

My objective is : To display a popin when the user clicks on a button To hide the popin when the user clicks elsewhere I previously implemented this solution successfully: Use jQuery to hide a DIV when the user clicks outside of it However, I wanted to ...

Error: Unable to access the 'CustomerId' property because it is undefined

Recently, I made some updates to my website. As part of the upgrade process, I switched to AngularJS v1.7.6 and JQuery v1.12.1. However, after making these changes, I encountered an error in my console log. TypeError: Cannot read property 'CustomerId ...

Is it possible to prevent the fade out of the image when hovering over the text after hovering over the div or image, causing the text to fade in?

Using React and CSS. I have set up my application to display a faded image on hover, with text that fades in over it. However, I am facing an issue where touching the text with my cursor removes the fade effect. Does anyone have a solution for preventing ...