1

I am having trouble with the following code:

var accounts = []

let accounts = await web3.eth.getAccounts((error, result) => {
    accounts = result;
    console.log(accounts);
});
console.log(accounts);

The first time I console.log(accounts), the accounts are successfully retrieved, but when I console.log(accounts) in the final line of code, I still get an empty array.

Any suggestions?

1

You are setting accounts = result, which then gets overwritten by the return of the function, which is nothing.

Instead, simply return result from the function rather than setting it:

var accounts = []

let accounts = await web3.eth.getAccounts((error, result) => {
    console.log(result);
    return result;
});
console.log(accounts);

Another option is to set accounts within the function and not return anything from the function itself:

var accounts = []

await web3.eth.getAccounts((error, result) => {
    accounts = result;
    console.log(accounts);
});
console.log(accounts);
  • When I attempt to return the result, I get the following report on my console: Uncaught SyntaxError: await is only valid in async function. This is confusing to me because in the following documentation, it confirms that web3.eth.getAccounts() is an async function. – Julian Martinez Jul 10 at 13:09
  • For whatever reason, the following code worked: var accounts = web3.eth.accounts; web3.eth.defaultAccount = accounts[0]; console.log(web3.eth.defaultAccount); Maybe I do not need to use an async function because I am using Ganache on local server: 7545 instead of a real blockchain. What do you think? – Julian Martinez Jul 10 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.