0

I have a function that calls a method via callback. When the promise resolves and returns a value after then, I am calling a method via await keyword. So it looks like

function test() {
  contract.setName(value).send({}).then(async function (data) {
    var result = await this.getResult(data);
  }
}

However, I get an error

Uncaught (in promise) TypeError: Cannot read property 'getResult' of undefined

Am I not allowed to use async/await method after callback?

bbusdriver
  • 1,577
  • 3
  • 26
  • 58
  • See the linked questions' answers, the problem is that you're using a traditional function, so `this` isn't what you expect it to be. BTW, you could make `test` `async` and make this simpler: `async function test() { const data = await contract.setName(value).send({}); const result = await this.getResult(data); }` (and be sure whatever calls it handles the fact it returns a promise, including handling rejections). – T.J. Crowder Jul 14 '19 at 07:10
  • If you can't make `test` `async`, then probably don't use an `async` callback for `then` as it doesn't buy you anything (and do handle rejections): `function test() { contract.setName(value).send({}) .then(data => { return this.getResult(data); }) .then(result => { // ...use `result`... }) .catch(error => { // ...handle/report error }); }` – T.J. Crowder Jul 14 '19 at 07:10
  • ok so you are saying either match both `async/await` or match `then` right? – bbusdriver Jul 14 '19 at 07:12
  • You *can* mix them, because `async` functions returns promises and you can return a promise from a `then` handler, but it probably confuses your meaning. In general, you want to keep it `async` as long as you can and handle the transition from `async` to non-`async` at the outermost level (the entry point of an event handler, for instance), which is also where you handle errors. Happy coding! – T.J. Crowder Jul 14 '19 at 07:23

0 Answers0