简体   繁体   中英

Javascript Loop through array and make call API for each value in array

Which javascript loop would be best for the below?

I am wanting to make API calls for each value in the array. Values could number more than what is shown below. I've looked through the loop types and also the promise all, I'm confused which to do 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 do I place this section

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);

Best and simplest would be to use a for loop and store each promise in an array. Once loop finishes you can use Promise.all(promiseArray) to perform actions based on resolved/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)

You can read more about Promise.all([])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Here is a small 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM