【问题标题】:Async / Await: Cannot access variable before initialization (javscript) [duplicate]异步/等待:初始化之前无法访问变量(javscript)[重复]
【发布时间】:2021-11-21 14:39:05
【问题描述】:

当我运行下面的代码时,我收到以下错误:

ReferenceError: Cannot access 'bar' before initialization.

有人可以帮我理解为什么会这样吗?据我所知,foo 函数应该等到 promise 解决(因为我使用的是 await,然后再转到 console.log(bar) 行。我在这里错过了什么?

function qux() {
  return Math.random();
}

async function bar() {
  let result = await qux();
  return result > 0.5;
}

async function foo() {
  let bar = await bar();
  console.log(bar);
}

foo();

【问题讨论】:

  • 你为什么要等qux?它不返回承诺。
  • 当你只有同步代码时,这里使用asyncawait是不协调的。

标签: javascript asynchronous async-await es6-promise


【解决方案1】:

问题出在函数foo()

bar 已经是一个函数,您在调用它时尝试分配给它,这可能不是您想要做的。

更改其中一个的名称。

function qux() {
  return Math.random();
}

async function bar() {
  let result = await qux();
  return result > 0.5;
}

async function foo() {
  let x = await bar();
  console.log(x);
}

foo();

【讨论】:

  • 啊,是的,你是对的——谢谢!
猜你喜欢
  • 2018-01-12
  • 2021-07-02
  • 2022-11-24
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多