0

I am calling two APIs in two different functions. Now I want the value of variable number in 2nd function. I think the two APIs are not executing simultaneously, which is why only the last value of first API is printing. Here's the code:

<script>
function getTrain(){
    var apiCall=(First API is called with predefined source n destination)
    $.getJson(apiCall,route);
    function route(objectName1){
        for(i=0;i<totalTrains;i++){
            var number=objectName1.Train[i].Number;

            var apiCall2=(Second API is called by passing the value of train number
                        from first API through loop)
            $.getJson(apiCall2,avail);
            function avail(objectName2){
                var seat=objectName2.SeatStatus;
                print("Train number: " + number + " Availability Status : " + seat);
            } 
        }
    }
}
</script>

Now as a print this output, my seat Availability Status is showing correctly for all train numbers, but the value of train number is always showing the last result of the json code of first API(that shows a list of train numbers between 2 stations).

1 Answers1

-1

To make your number available in the callback for the second API call, you might use a closure:

var number = ...;
var apiCall2 = ...;
$.getJson(apiCall2, (result) => { avail(number, result); });

function avail(number, objectName2) {
  ...
}

The value of number will be stored in the callback function for $.getJson and will be passed down to avail as a parameter.

afenster
  • 3,468
  • 19
  • 26