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 => {

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.

  • what is the web3 version you use? Mar 27 '18 at 18:29
  • Things related to .then have changed with version, you should specify your web3 version in question.
    – Ayushya
    Mar 27 '18 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
    Mar 27 '18 at 19:15
  • did you solve this problem?
    – Sajuuk
    Jul 31 '18 at 12:45

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

  • 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
    Jul 31 '18 at 12:44

Try wrapping it in an asynchronous function:

private async deployContract(): Promise<string> {
  return Promise.resolve('Check done');

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.