【发布时间】:2022-12-01 02:40:50
【问题描述】:
async function run(teamKey) {
let { data } = await axios.get(URL);
const { rounds } = data;
let goals = 0;
rounds.forEach((matchday) => {
matchday.matches.forEach((match) => {
if (match.team1.key == teamKey) {
goals += match.score1;
} else if (match.team2.key == teamKey) {
goals += match.score2;
}
});
});
console.log("goals: ", goals); // I can see the goals in console log
return goals; // but what's being returned is a pending promise
}
console.log("run(): ", run("arsenal"));
据我所知, run() 的执行完成并在 axios.get() 解决之前返回了一个未决的承诺。据我所知,只有一种方法可以实现目标,那就是在 run() 之后链接 .then()。有没有办法让 run() 函数返回可以稍后在代码中使用的目标,而无需使用链式 .then()?
我尝试了所有方法,创建了另一个调用 run() 的异步函数并返回了 run() 的返回值,但没有成功。
【问题讨论】:
-
由于
run是一个async函数,它必然会返回一个承诺。这就是async关键字的作用(即允许您使用await关键字)。您要么需要调用.then承诺,要么将您的代码放入async函数和await承诺中。