Search code examples
javascriptnode.jsasync-awaites6-promise

promises scope using await and async


      var accountA;
       var  accountB;
      accounts = async () => {
        accountA = await server.loadAccount(Apub)

        console.log(accountA)
        accountB = await (server.loadAccount(Bpub))
    }

  accounts()

  console.log(accountA);

1) Apub is my public key which i have already declared

2)when i am printing the

accountA

inside the function it is showing me complete details from accountA

3) when i do console.log outside the function, the output is

undefined

4) i have declared the variables outside the function as the global scope

please help me


Solution

  • Although you are using await inside the function you are not waiting till it you get a response while you call accounts which is an async function

    var accountA;
    var  accountB;
    accounts = async () => {
        accountA = await server.loadAccount(Apub)
    
        console.log(accountA)
        accountB = await (server.loadAccount(Bpub))
    }
    
    accounts().then(() => {
        console.log(accountA);
    })
    

    If you have the above code in a function which is async then you could use await with accounts too

    await accounts()