如何控制台日志 - 或对从异步函数内部返回的数据执行任何操作?
例: 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 文件中的所有信息并使用它。 例如,我想获取"第一"和"第二"并将它们添加到div 中。 与"FirstA"和"FirstB"以及"SecondA"和"SecondB"相同...等等。
现在就目前而言,我得到了承诺{:未定义}
任何帮助将不胜感激。
---------更新---------
如果我在函数内运行控制台日志,则可以看到 json 数据,但我需要访问函数外部的数据。
哔叽
两个问题:
-
若要设置
async
函数创建的承诺的解析值,必须使用async
函数本身的return
语句。代码在getJSON
回调(被忽略)中具有return
,而不是async
函数本身。 -
要获取
async
函数的解析值,您必须await
它(或通过then
等以旧方式使用它的承诺)。
对于 #1,您可以返回await
inggetJSON
的结果:
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
来消费其承诺:
getData().then(data => {
console.log(data);
});
旁注:您的getData
隐藏错误,将它们转换为值为undefined
的分辨率,这通常不是一个好主意。相反,请确保它传播错误:
catch (error) {
console.log("error" + error);
throw error;
}
然后,自然地,确保任何使用getData
的东西处理或传播错误,确保某处的某些东西确实处理了它(否则,你会得到一个"未处理的拒绝"错误)。
重新发表您的评论
如何从函数外部的日志访问 JSON 文件中的"内容"?
getData
的异步结果/解析值是 JSON 定义的对象(它不再是 JSON,它已被解析)。所以你会在上面使用.stuff
,例如:
// In an `async` function
console.log((await getData()).stuff);
// Or using `then`:
getData().then(data => {
console.log(data.stuff);
});
我使用以下方式。创建一个异步函数,如下所示:
private consoleLogAsync = async (message: string, other?: any) => {
await new Promise((resolve) => setTimeout(resolve, 0)).then(() => console.info(message, other));
};
在您想要记录的异步函数中使用它,例如:
await this.consoleLogAsync('myMessage', myObject);