5

How to refer to class instance when called from an async method.

class Senders {
  callSendAPI() {
    //Some code here
  }
  sendText() {
    this.callSendAPI();
  }
  async sendCards() {
    var dbpromise = await db.call();
    console.log('this= ', this);
    this.callSendAPI();
  }
}
export {Senders};

this= undefined

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
ishandutta2007
  • 16,676
  • 16
  • 93
  • 129
  • are you using babel or something else? – Daniel A. White Feb 24 '17 at 19:04
  • if so that sounds like a nasty bug in that converter. – Daniel A. White Feb 24 '17 at 19:05
  • 7
    How is `sendCards()` called? You need to show that code because that is what determines the value of `this` inside of `sendCards()`. The problem is likely in your calling code which you don't show. I will hazard a guess that you are passing `obj.sendCards` as a callback and that is why it isn't working. If my guess is correct, see [How to get callback to work with “this” in class scope](http://stackoverflow.com/questions/15048775/how-to-get-callback-to-work-with-this-in-class-scope/15048802#15048802). – jfriend00 Feb 24 '17 at 19:08
  • Agree with jfriend00. The code you posted should work how you expect it to work. But in js the value of `this` is determined NOT by how you define functions and classes but by how you call a function. So you're not exactly showing what's causing the bug – slebetman Feb 24 '17 at 19:49
  • Perhaps you should read the accepted answer to this to understand how `this` really work. Note that there is nothing in the answer related to classes or async because they're irrelevant: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Feb 24 '17 at 19:51
  • thanks @jfriend00 it was callback issue , bind solved the problem. Bind is fine for me as my code is a server so I need not bother about making it browser compatible. – ishandutta2007 Feb 25 '17 at 03:55
  • `async/await` is *not* part of ES2016 (and whether or not a function is `async` has no influence on its `this` value). – Felix Kling Mar 01 '17 at 14:35

1 Answers1

2

The issue is either with whatever transpiler you are using, if you are using one, or the context of the function given the way it is invoked. I ran the following snippet in NodeJS v7.x and it worked just fine, showing the value of this was a class instance of Senders.

class Senders {
  async sendCards() {
    console.log('this= ', this);
  }
}

new Senders().sendCards();

If you determine that it isn't your transpiler, then try controlling the execution context by using bind or call/apply when you are invoking the function.

rdgd
  • 1,451
  • 2
  • 18
  • 33