-1

Can someone tell me why await is not working here?

const Web3 = require('web3');

web3 = new Web3(new Web3.providers.HttpProvider("http://<ip>:8545"));

let accounts = (async () => await web3.eth.getAccounts())();

// await was not working, here I get a promise
console.log(accounts);

// if I wait with a timeout I get my accounts
setTimeout(() => console.log(accounts), 5000);
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • I tried this, but `await` is just allowed in functions, this is why I built this function around. –  Dec 22 '18 at 14:09
  • Does this answer your question? [How does javascript async/await actually work?](https://stackoverflow.com/questions/57160341/how-does-javascript-async-await-actually-work) – TylerH Mar 03 '23 at 17:12

2 Answers2

3

Your console.log has to be inside the inline async function.

(async () => {
   accounts = await web3.eth.getAccounts()
   console.log(accounts);
}
)();
Sumer
  • 2,687
  • 24
  • 24
1

It doesn't work like that. An async function returns a promise. console.log outside async function will not wait for an await. You can only stop your code INSIDE an async function.

async function getData() {
    const answer = await web3.eth.getAccounts()
    console.log(answer) /* this console.log will be wait */
    return answer
}

getData().then(answer => console.log(answer))

If it'd works like that (holding code outside a function) It'd stop all process on a browser (like the alert function) and an user'd be have to wait too.

pantyuhind
  • 119
  • 4