[Ethereum] Undefined results for “web3.eth.accounts” in truffle console

truffleweb3js

truffle(development)> web3.eth.accounts[0]

gives output as "undefined"

truffle(development)> web3.eth.accounts

instead of showing all accounts details gives the below output

Accounts {

currentProvider: [Getter/Setter],


_requestManager:

RequestManager {

 provider:

  HttpProvider {
    host: 'http://127.0.0.1:7545',

    httpAgent: [Agent],
    timeout: 0,

    headers: undefined,

    connected: true,

    send: [Function],

   ......blah...blah

but…

truffle(development)> web3.eth.getAccounts

is working. please help

Best Answer

from @goodvibration in the comments :

web3.eth.accounts is deprecated.

That is true. in the newer version of web3.js web3.eth.getAccounts returns a promise, so that is why doing :

var accounts = web3.eth.getAccounts();
accounts[0];

will return undefined.

TLDR: use this code instead

web3.eth.getAccounts().then(function(acc){ accounts = acc })
accounts[0]