0

I have run into something that seems pretty weird to me, although there's a good chance it's just a basic knowledge gap issue. As you can see, the following execution within the Node console produces the desired result, i.e. outputting the number of account addresses stored in accounts:

> var Web3 = require("web3");
undefined
> var web3 = new Web3(new 
Web3.providers.HttpProvider("http://localhost:8545"));
undefined
> var accounts;
undefined
> web3.eth.getAccounts().then(_accounts => { accounts = _accounts });
Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
> console.log(accounts.length);
10
undefined

However, running an external js file containing the exact same code

var Web3 = require("web3");

var web3 = new Web3(new 
Web3.providers.HttpProvider("http://localhost:8545"));

var accounts;
web3.eth.getAccounts().then(_accounts => { accounts = _accounts });

console.log(accounts.length);

produces the following error:

➜  ethtest node test.js
/home/brandon/ethtest/test.js:8
console.log(accounts.length);
                    ^

TypeError: Cannot read property 'length' of undefined
    at Object.<anonymous> (/home/brandon/ethtest/test.js:8:21)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:383:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:496:3

What could be the difference? Am I simply attempting something that cannot be done? Any help will be much appreciated, and thanks in advance!

2

The issue you are experiencing is because the code is executed asynchronously.

Then then clausule is executed when the call to getAccounts has returned the result. But the console.log is executed immediately after getAccounts and before the then function.

A solution is to also wait before logging.

var Web3 = require("web3");

var web3 = new Web3(new 
Web3.providers.HttpProvider("http://localhost:8545"));

var accounts;
web3.eth.getAccounts()
.then(_accounts => { accounts = _accounts })
.then(() => { console.log(accounts.length); });
  • 1
    Thanks! This is the correct answer, minus the semicolon after .then(_accounts => { accounts = _accounts }). – Brandon M. Jan 3 '18 at 17:16
  • 1
    You are right, I did forgot to remove the semicolon. It is fixed now, thanks! – Ismael Jan 3 '18 at 18:43
0

try, var accounts = web3.eth.accounts;

0

Try the following -

web3.eth.getAccounts().then(_accounts => { 
accounts = _accounts 
console.log(accounts.length)
});

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.