Mike
Mike

Reputation: 67

Javascript update multiple json files access is a single function

I am looking to get the data from 2 json files every 60 seconds. One file contains news articles, and the second file contains comments relating to each article.

I can download the comments for updates every 60 seconds, and pass the json to the results function.

function updateData() {

 var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");

 xobj.onreadystatechange = function () {
      if (xobj.readyState == 4 && xobj.status == "200") {
        //showResults(xobj.responseText);
        showResults(JSON.parse(xobj.response));
      }
 };

 xobj.open("GET", "comments.json", true);
 xobj.send();

 setTimeout(updateData, 60000);
}

However, how do I open 2 json files, and pass the results to the showResults function using the callback?

I am trying to display the topics and comments together. So for each topic, get the comments for that topic. I can get this working by using globals, but I think that is a poor approach.

  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
    topics = JSON.parse(xobj.response);
    }
  };

  xobj2.onreadystatechange = function () {
    if (xobj2.readyState == 4 && xobj2.status == "200") {
    comments = JSON.parse(xobj2.response);
  }
 };

I saw a solution that downloaded multiple json files, but then we do not know what file would download first, so I would be unable to use:

showResults(JSON.parse(xobj.response), JSON.parse(xobj2.response));

Because it is asynchronous, and the order could differ, and showResults would need to expect the order to be (topics, comments).

I am looking for a way that the current function can have access to the data from both of the files.

 function showResults(json) {
 // Have both here to display
 }

Is using globals acceptable?

Upvotes: 1

Views: 89

Answers (1)

machineghost
machineghost

Reputation: 35813

You want to use Promise.all to combine the two promises that you get from reading the two files. This will give you a new promise that resolves when both of the other promises are ready, and it will resolve with an array of both promises' results.

For instance:

const combinedPromise = Promise.all([readFile1(), readFile2()]);
combinedPromise.then(([file1, file2]) => // ... code that uses both files

Upvotes: 1

Related Questions