Javascript 异步函数控制台记录返回的数据



如何控制台日志 - 或对从异步函数内部返回的数据执行任何操作?

例: 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 数据,但我需要访问函数外部的数据。

哔叽

两个问题:

  1. 若要设置async函数创建的承诺的解析值,必须使用async函数本身的return语句。代码在getJSON回调(被忽略)中具有return,而不是async函数本身。

  2. 获取async函数的解析值,您必须await它(或通过then等以旧方式使用它的承诺)。

对于 #1,您可以返回awaitinggetJSON的结果:

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);

最新更新