Web3js

在啟動節點控制台之前嘗試將帳戶初始化為全域變數

  • January 4, 2018

基本上,我正在嘗試執行一個腳本來初始化我在 Node 控制台會話期間需要的所有變數。腳本如下所示:

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({});

到目前為止,一切正常,直到設置accounts變數。執行腳本並呼叫它會產生以下結果:

➜  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)

我很確定我誤解了一些簡單的東西,但到目前為止,我一直無法弄清楚。任何幫助將非常感激。謝謝!

您有一個比賽條件,即在require('repl').start({});執行之前accounts = _accounts;執行。這是因為web3.eth.getAccounts()非同步執行。你應該擁有的是

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

引用自:https://ethereum.stackexchange.com/questions/35060