我如何控制日志 - 或者对从异步函数内部返回的数据做任何事情?
例子: JS 文件:
async function getData(){
try {
$.getJSON('./data.json', (data) => {
return data;
});
} catch(error) {
console.log("error" + error);
} finally {
console.log('done');
}
}
console.log(getData());
JSON 文件:
{
"stuff": {
"First": {
"FirstA": {
"year": [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
},
"FirstB": {
"year": [2007, 2008, 2009, 2010, 2011, 2012],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
}
},
"Second": {
"SecondA": {
"year": [2002, 2003, 2004, 2005, 2006],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
},
"SecondB": {
"year": [2007, 2008, 2009, 2010, 2011, 2012],
"Categories": ["Suspension", "Electrical", "Performance", "Motor"]
}
}
}
}
如何返回/获取对 JSON 文件中所有信息的访问权并使用它。例如,我想将“First”和“Second”添加到一个 div 中。与“FirstA”和“FirstB”以及“SecondA”和“SecondB”...等相同。
就目前而言,我得到Promise {: undefined}
如有任何帮助,我们将不胜感激。
--------更新------------
如果我在函数内部运行控制台日志,那么我可以看到 json 数据,但我需要访问函数外部的数据。
谢尔盖
最佳答案
两个问题:
要设置
async
函数创建的 promise 的解析值,您必须使用return
语句async
函数本身。您的代码在getJSON
回调(被忽略)中有一个return
,而不是async
函数本身。要获取
async
函数的解析值,您必须await
它(或以旧方式使用它的 promise ,通过then
等)。
对于 #1,您可以返回 await
ing getJSON
的结果:
async function getData() {
try {
return await $.getJSON('./data.json').promise();
}
catch (error) {
console.log("error" + error);
}
finally {
console.log('done');
}
}
对于 #2,您需要 await
您的函数(这又需要在 async
函数中):
console.log(await getData());
...或者通过 then
消费它的 promise :
getData().then(data => {
console.log(data);
});
旁注:您的 getData
隐藏了错误,将它们转化为值为 undefined
的解决方案,这通常不是一个好主意。相反,确保它传播错误:
catch (error) {
console.log("error" + error);
throw error;
}
然后,自然而然地,确保任何使用 getData
的东西都处理或传播错误,确保某个地方确实处理了它(否则,你会得到一个“未处理的拒绝”错误)。
回复你的评论
how would I access the "stuff" in the json file from the log outside the function?
getData
的异步结果/解析值是JSON定义的对象(已经不是JSON了,已经解析过了)。所以你会在上面使用 .stuff
,例如:
// In an `async` function
console.log((await getData()).stuff);
// Or using `then`:
getData().then(data => {
console.log(data.stuff);
});
关于Javascript 异步函数控制台记录返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48036038/