File based API call synchronously in JavaScript

SOLVED: I solved my problem by executing each XMLHttpRequiest () recursively. Basically at the end of my xhr.onload, I would make another request and actively check if I got to the end of my data - when I return.

I'm new to JavaScript and a little familiar with the D3 Library. I am trying to read a CSV file from my computer using the D3 library and send certain information from my file to the API via XMLHttpRequest ().

For every API call that returns a JSON object to me, I save that object in a dataset for later use. I am trying to do this so that the entire CSV file is read and processed before I work on a given dataset, however I am facing a problem as the API calls are asynchronous.

My code looks something like this:

var myData = [];

d3.csv("myFile.csv", function(data)
{
    for (var i = 0; i < data.length; i++)
        // Get appropriate data from data object
        // Make API call with XMLHttpRequest() and store in myData array
});

// Handle fully updated myData array here

      

Be that as it may, my code is currently going through my loop almost instantly and making all API calls asynchronous and then continuing to work on my data without waiting for an update.

Is there a way to ensure that my CSV file has been processed and all API calls have returned before I can work with this dataset? I have tried callbacks and promises but with no success.

+3


source to share


2 answers


You can easily do this with a simple counter

var counter = 0;
var myData = [];

d3.csv("myFile.csv", function(data)
{
  for (var i = 0; i < data.length; i++){
  // Get appropriate data from data object
    $.get("your/api/path", function(result){
      counter++;  // this is important. It increments on each xhr call made.
      myData.push(result); 
      if(counter === data.length) cb(myData); // This will check if the current xhr request is the last xhr request. If yes then call our cb function.
    });
  }
});

function cb(data){
  // This will run only when all the http requests are complete
  // Do something with data
}

      



All this code does this, it makes sure that all our requests must complete first before calling our cb function (this is where you write your following logic). This approach ensures that cb will only run when all xhr requests have completed.

+3


source


I think the answer in this post might help d3: make the d3.csv function synchronous



You can also use the Promise API.

0


source







All Articles