2

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

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

7 Comments

Getting data from JSONPlaceholder APIs jsfiddle.net/L9h1ctrs/1
This is great Pramod, very helpful, I'm still puzzled, I make the API call, i dont understand the .then and .catch also in which place would i enter my Data/Dept values? Would that still come after the promise all or inside?
When you execute an async task in JS i.e. API, setTimeout, etc, JS will queue tasks as it doesn't know when they'll finish it's executing also, as it helps the main thread to do some other tasks instead of waiting for queued tasks. Meantime it will check if queued tasks are finished regular intervals. Talking about then, it means your task is resolved with data and catch, the task is rejected with error(s). You can read more about Promises developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. Is has a diagram that would help you understand Promises.
I couldn't understand what you meant by 'which place would I enter my Data/Dept values?', It would help if you could elaborate a little, maybe with some examples. :)
It may not work as it is but may serve as a skeleton for your code. jsfiddle.net/u2sbmjov
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.