【问题标题】:How to return from a function a value obtained from resolved promise inside that function? [duplicate]如何从函数返回从该函数内部已解决的承诺中获得的值? [复制]
【发布时间】: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 承诺中。

标签: javascript es6-promise


【解决方案1】:

正如您在 run 函数的开头编写了 async 关键字,这意味着该函数将是异步函数并将返回一个承诺,因此要在控制台中获取数据,您必须使用 then 和 @ 处理承诺调用此函数时的 987654324@语句。

像这样:

run("arsenal")
    .then((response) => { console.log("run(): ", response) })
    .catch((error) => { console.log(error) })

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2019-01-23
    • 2017-04-05
    相关资源
    最近更新 更多