加载多个json,然后执行函数



我在一个变量中有一个JSON文件列表,我想将这些文件的内容加载到一个对象中。json文件有两个键:元数据和输出。

完成后,我想调用一个函数来生成一个表列表。如果我只有一个文件,我就能做到这一点。我使用的代码是:

jQuery.getJSON(filePath, function(data) {
jQuery.each(data, function(key, val){
if ( key === "outputs"){
new tableGenerator(val);
};
});
});

当我试图从不同的文件中获取数据时,我会得到一个空变量。要加载不同的文件,我使用:

var fileList = ["dataFolder/data1.json",
"dataFolder/data2.json",
"dataFolder/data3.json"]
var jsonData = [];
jQuery.when(
fileList.forEach( file => {
jQuery.getJSON(file, function(data) {
jQuery.each(data, function(key, val){
if ( key === "outputs"){
jsonData = jsonData.concat(val);
}; 
});
});
})
).then(function(){
console.log(jsonData);
new tableGenerator(jsonData);
})

我在javascript中不正常工作,也不明白为什么通常在填充jsonData处理程序之前执行tableGenerator函数。

代码中的任何注释都是受欢迎的(风格,不推荐使用…(,因为我不是javascript开发人员,可能很多事情都会以一种不常见的方式完成。

当期望deferred作为参数时,您给它的是deferred。您需要返回延迟的getJSON调用返回,并将其设置为when

var fileList = [
"https://jsonplaceholder.typicode.com/todos/1",
"https://jsonplaceholder.typicode.com/todos/2",
"https://jsonplaceholder.typicode.com/todos/3"
]
const calls = fileList.map(path => $.getJSON(path))
$.when(...calls).then((...responses) => {
const yourData = responses.map(([json]) => json);
console.log(yourData);
// call table code
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

没有jQuery

var fileList = [
"https://jsonplaceholder.typicode.com/todos/1",
"https://jsonplaceholder.typicode.com/todos/2",
"https://jsonplaceholder.typicode.com/todos/3"
]
const calls = fileList.map(path => fetch(path).then(response => response.json()))
Promise.all(calls).then(yourData => {
console.log(yourData);
// call table code
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

json文件的get请求是异步的。也就是说,你需要正确地等待它的发生。

我建议在vanilla JS中使用异步/等待方法,而不使用jQuery(也就是我们生活在2022年(

const fileList = ["dataFolder/data1.json", "dataFolder/data2.json", "dataFolder/data3.json"]

async function getData(url) {
const request = await fetch(url)
const response = await request.json()
return response
}
async function generateTables(list){
let tablesData = [];
for (const url of list) {
const data = await getData(url)
tablesData.push(...data?.outputs) //get only "outputs"
}
return [...tablesData]
}
generateTables(fileList).then(result => {
console.log(result);
new tableGenerator(result);
})

这是一个异步问题。这是JavaScript的典型行为,您声明一个函数,该函数将在数据准备就绪时启动。声明之后,JavaScript运行下一个语句。

请参阅如何让getJSON在运行其余代码之前等待?以更经典的同步模式转换代码。

await关键字是在ECMAScript 2017中引入的,它允许无代码的JavaScrip特定。

最新更新