3

I am having an error with Web3. After going through all possibilities I decided to post a question hoping for someone with a solution.

The error I keep getting is:

TypeError: Cannot read property 'then' of undefined

web3.eth.getAccounts().then(accounts => {
   web3.eth.getBalance(accounts[0]).then(balance => {
      console.log(balance);
    }
}



Note: this exact same code is running fine on two other servers. I do have the exact same versions of Truffle, React..etc as the other two.

Any solutions will be appreciated! Thanks in advance.

4
  • what is the web3 version you use? Commented Mar 27, 2018 at 18:29
  • Things related to .then have changed with version, you should specify your web3 version in question.
    – Ayushya
    Commented Mar 27, 2018 at 19:10
  • You need at least web3 v1.0 because it has support for promises, for version v0.20 it only supported callbacks, you have to use a third party library like bluebird to promisify functions.
    – Ismael
    Commented Mar 27, 2018 at 19:15
  • did you solve this problem?
    – Sajuuk
    Commented Jul 31, 2018 at 12:45

2 Answers 2

0

have you tried to add a catch in order to output the stacktrace of your error ?

Just add at the end of your promise chain : then(account => {...}).catch( err => { console.log(err); }

You'll then be able to see in the console the stacktrace of the error and distinguish if it is accounts or accounts[0] which is undefined.

If it is accounts[0], ensure your web3 instance is connected. If is is the whole accounts object, ensure you use Web3.js v1.x.x and not v.0.2.x

1
  • unfortunately somehow my error was thrown before this catch was in effect, possibly because I used jQuery. jQuery.Deferred exception: Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined
    – Sajuuk
    Commented Jul 31, 2018 at 12:44
0

Try wrapping it in an asynchronous function:

private async deployContract(): Promise<string> {
  web3.eth.getAccounts().then...
  ...
  return Promise.resolve('Check done');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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