0

When I run the code below I get the following error:

ReferenceError: Cannot access 'bar' before initialization.

Could someone help me understand why this is happening? As far as I can tell, the foo function should wait until the promise resolves (since I'm using await before moving onto the console.log(bar) line. What am I missing here?

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();
Andy
  • 53,323
  • 11
  • 64
  • 89
bugsyb
  • 4,977
  • 7
  • 28
  • 39

1 Answers1

5

The problem is in the function foo()

bar is already a function and you're trying to assign to it while calling it, which probably isn't what you meant to do.

Change the name of one of them.

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();
Andy
  • 53,323
  • 11
  • 64
  • 89
DexieTheSheep
  • 409
  • 6
  • 12