javascript Javascript异步函数控制台记录返回的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48036038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript async function console log the returned data
提问by Sergio
How can I console log - or do any thing with the data returned from inside an async function?
如何控制台日志 - 或者对从异步函数内部返回的数据执行任何操作?
example: JS FILE:
示例: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 FILE:
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"]
}
}
}
}
How can I return / get access to all the information in the JSON file and work with it. for example I'd like to take the "First" and "Second" and add them to a div. Same with "FirstA" and "FirstB" and "SecondA" and "SecondB"...and so on.
我如何返回/访问 JSON 文件中的所有信息并使用它。例如,我想将“第一”和“第二”添加到 div 中。与“FirstA”和“FirstB”和“SecondA”和“SecondB”相同......等等。
Right now as it stands, I get Promise {: undefined}
现在,我得到Promise {: undefined}
Any help would be greatly appreciated.
任何帮助将不胜感激。
---------UPDATE---------
- - - - -更新 - - - - -
If I run the console log inside the function I then can see the json data, but I need access to the data outside the function.
如果我在函数内部运行控制台日志,则可以看到 json 数据,但我需要访问函数外部的数据。
Serge
哔叽
回答by T.J. Crowder
Two issues:
两个问题:
To setthe resolution value of the promise created by the
asyncfunction, you have to use areturnstatement from theasyncfunction itself. Your code has areturnin thegetJSONcallback (which is ignored), not theasyncfunction itself.To getthe resolution value of an
asyncfunction, you mustawaitit (or consume its promise in the older way, viathen, etc.).
要设置
async函数创建的承诺的分辨率值,您必须使用函数本身的return语句async。您的代码return在getJSON回调中有一个(被忽略),而不是async函数本身。要获取
async函数的分辨率值,您必须使用await它(或以较旧的方式使用它的 promise,通过then等)。
For #1, you could return the result of awaiting getJSON:
对于#1,您可以返回awaiting的结果getJSON:
async function getData() {
try {
return await $.getJSON('./data.json').promise();
}
catch (error) {
console.log("error" + error);
}
finally {
console.log('done');
}
}
And for #2, you'd need to either awaityour function (this would, in turn, need to be inside an asyncfunction):
对于#2,您需要使用await您的函数(反过来,这需要在async函数内部):
console.log(await getData());
...or consume its promise via then:
...或通过then以下方式消费其承诺:
getData().then(data => {
console.log(data);
});
Side note: Your getDatahides errors, turning them into resolutions with the value undefined, which is generally not a good idea. Instead, ensure that it propagates the error:
旁注:您getData隐藏错误,将它们转换为具有 value 的分辨率undefined,这通常不是一个好主意。相反,请确保它传播错误:
catch (error) {
console.log("error" + error);
throw error;
}
Then, naturally, ensure that anything using getDataeither handles or propagates the error, making sure something somewhere doeshandle it (otherwise, you get an "unhandled rejection" error).
然后,自然地,确保任何使用getData处理或传播错误的东西,确保某处确实处理它(否则,您会收到“未处理的拒绝”错误)。
Re your comment
回复你的评论
how would I access the "stuff" in the json file from the log outside the function?
我将如何从函数外部的日志访问 json 文件中的“东西”?
The async result / resolution value of getDatais the object the JSON defined (it's no longer JSON, it's been parsed). So you'd use .stuffon it, e.g.:
的异步结果/解析值getData是 JSON 定义的对象(它不再是 JSON,它已被解析)。所以你会使用.stuff它,例如:
// In an `async` function
console.log((await getData()).stuff);
// Or using `then`:
getData().then(data => {
console.log(data.stuff);
});

