2

javascript / Node.js

how can I retrieve a reference to this/object inside a promise.then ?

var controller = new MyController(params);

controller.action_send();

/////////////////////////////////

class MyController{

    constructor(params)
    {
        this.params = params;
    }

    action_send()
    {
        var promise = ext_lib.send();


        promise.then(
            function(details) {

                this.action_save(details);
                //(node:27014) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'action_save' of undefined
           });
   }

    action_save(details)
    {  
     save (this.params, details);
    }   
}

a PHPStorm warning says Warns against a common mistake of trying to reference a member of an ECMAScript class via this. qualifier in a nested function that is not a lambda. this in a nested function that is not a lambda is the function's own 'this' and doesn't relate to the outer class.

tks from now

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Simone Bonelli
  • 411
  • 1
  • 5
  • 18
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Quentin Aug 13 '18 at 15:37

3 Answers3

2

You want to use an arrow function: (details) => {...}. This will make the scope the same as outside of the function, and so this should be your class.

I would also recommend looking up the difference between the function syntax and the => syntax, someone can probably explain it better than I.

obermillerk
  • 1,560
  • 2
  • 11
  • 12
2

Use an arrow function.

Unlike a regular function, an arrow function does not bind this. Instead, this is bound lexically (i.e. this keeps its meaning from its original context).

Here are more details about it Arrow Functions

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Pato Salazar
  • 1,447
  • 12
  • 21
1

Just to add to the above answers, this is how your code should look like

promise()
.then(function (results) {
  }.bind(this)
).catch(...);

Make sure your bind is just before closing then()

Mohamed Salem Lamiri
  • 5,767
  • 6
  • 34
  • 47