javascript - 数组上的 JavaScript Async/Await console.log() 返回空
问题描述
你好 Stack Overflow 社区,我来找你一个与 JS async/await 相关的问题。我正在尝试调用异步函数,然后将数组记录到异步函数将结果推送到控制台的位置。如果我直接在控制台中这样调用它:
console.log(Page.data) - 我可以看到它有结果,但如果它在单击按钮时被调用,它会记录一个空数组。
// It is a nested object so do not worry if you don't exactly understand where Page.data comes from
Page.data = []
async function f1() {
// Fetch JSON data
// Process data
// Pushes at some point to the Page.data array
}
async function f2() {
// Fetch JSON data
// Process data
// Pushes at some point to the Page.data array
}
async function f3() {
// Fetch JSON data
// Process data
// Pushes at some point to the Page.data array
}
async function load(loader) {
let fn = async function() {};
if(condition1) fn = f1;
else if(condition2) fn = f2;
else fn = f3;
// This is the line that makes me problems
// According to documentation async functions return a promise
// So why would the array in the case be empty?
// Since I am telling it to display after the function is done
await fn(loader).then(console.log(Page.data))
}
这只是我的代码和逻辑的模板。我希望你能明白我要去哪里。您的帮助将不胜感激。
解决方案
await 表达式导致异步函数执行暂停,直到 Promise 被解决(即完成或拒绝),并在完成后恢复异步函数的执行。恢复时,await 表达式的值是已实现的 Promise 的值。
例如(这是一个带有一些添加注释的 MDN 示例):
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
// note that here, you are "awaiting" the RESOLVED RESULT of the promise.
// there is no need to "then" it.
var x = await resolveAfter2Seconds(10);
// the promise has now already returned a rejection or the resolved value.
console.log(x); // 10
}
f1();
所以你会“等待”你的函数,这将阻止执行,直到承诺解决或拒绝。在该行之后,您将运行您的 console.log,它会按预期记录。简短的回答,“删除 then”。
我应该补充一点,如果“等待”函数的结果不是一个承诺,它会被转换为一个承诺(所以从技术上讲,不需要返回一个承诺,它会为你包装你的返回值)。
推荐阅读
- r - R curl::curl_download“传输已关闭,剩余 N 个字节要读取”
- java - 将数据从一个活动传递到另一个活动而不启动它的最佳方法是什么?
- c# - 使用 C# 服务执行各种频率的查询
- perl - How do I read a file into an array in Perl but correctly handle duplicates?
- python - 循环请求
- asp.net-core - ViewModel 不向 Post 方法返回数据
- pandas - 熊猫数据框中的条件搜索
- python - 如何平滑 matplotlib 中的折线图?
- xamarin - Xamarin 无法编译:参数 System.Collections.Generic.List`1[T] queryArgs
- react-native - 无法解析依赖树 React Native