0

Basically, I am trying to run a script that initializes all the variables I'll need during my Node console session. The script looks like this:

global.Web3 = require('web3');
global.web3 = new Web3(new 
Web3.providers.HttpProvider('http://localhost:8545'));

global.Tx = require('ethereumjs-tx');

global.solc = require('solc');

global.accounts;
web3.eth.getAccounts().then(_accounts => {
    accounts = _accounts;
});
require('repl').start({});

So far, everything works fine, until time to set the accounts variable. Running the script and calling it produces the following:

➜  ethtest node init.js
> accounts
ReferenceError: accounts is not defined
    at repl:1:1
    at ContextifyScript.Script.runInContext (vm.js:35:29)
    at REPLServer.defaultEval (repl.js:342:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:539:10)
    at emitOne (events.js:96:13)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:232:10)
    at REPLServer.Interface._line (readline.js:583:8)

I'm pretty sure I'm misunderstanding something simple, but so far, I've been unable to figure it out. Any help would be much appreciated. Thanks!

1

You have a race condition where require('repl').start({}); runs before accounts = _accounts; runs. This is because web3.eth.getAccounts() runs asynchronously. What you should have instead is

web3.eth.getAccounts().then(_accounts => { accounts = _accounts; require('repl').start({}); });

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.