【发布时间】:2020-01-22 22:15:57
【问题描述】:
您好 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 来获取分辨率值,或者使用promise.then(...)以便在promise 解决后启动代码。选择其中之一,而不是两者。 -
@Mike'Pomax'Kamermans 所以你建议我应该做 fn().then()?
-
await fn(loader); console.log(Page.data); -
既然你使用了 await 关键字,那么你可以这样做:
await fn(loader); console.log(Page.data); -
或者只是不使用 await 关键字,它可能会起作用
标签: javascript asynchronous async-await