javascript - 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?
解决方案
您想使用Promise.all
从读取这两个文件中获得的两个 Promise 组合起来。这将为您提供一个新的 Promise,当其他两个 Promise 都准备好时它会解析,并且它将使用两个 Promise 的结果数组来解析。
例如:
const combinedPromise = Promise.all([readFile1(), readFile2()]);
combinedPromise.then(([file1, file2]) => // ... code that uses both files
推荐阅读
- json - 从字符串在 VB.net 中创建 Json 并在 WebRequest 中使用它
- typescript - 所有接口(键:值)值的板条箱类型
- angular - 量角器找不到动态创建的元素
- spring - 使用 KafkaStream 从主题中读取 Avro 消息,将它们转换为字符串/json 并存储在 AWS S3 存储桶中
- jquery - 如何在 angular2 应用程序中实现日期选择器?
- cucumber - Eclipse 中的黄瓜设置
- php - 基于用户元数据国家设置的 Echo AFC 字段
- powershell - 如何调用另一个函数并捕获这两个函数中的错误?
- cartesian-coordinates - 什么是具有球对称性的反应扩散算法的良好拉普拉斯算子?
- css - SVG 动画:告诉关键帧“什么都不做”