首页 > 解决方案 > 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?

标签: javascriptjsonfunction

解决方案


您想使用Promise.all从读取这两个文件中获得的两个 Promise 组合起来。这将为您提供一个新的 Promise,当其他两个 Promise 都准备好时它会解析,并且它将使用两个 Promise 的结果数组来解析。

例如:

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

推荐阅读