Search code examples
javascriptasynchronousasync-awaites6-promise

Async / Await: Cannot access variable before initialization (javscript)


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();


Solution

  • 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();