Simone Bonelli
Simone Bonelli

Reputation: 421

how can I retrieve a reference to this in a promise.then ()?

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

Upvotes: 2

Views: 1746

Answers (3)

Pato Salazar
Pato Salazar

Reputation: 1477

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

Upvotes: 3

Mohamed Salem Lamiri
Mohamed Salem Lamiri

Reputation: 6077

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()

Upvotes: 1

obermillerk
obermillerk

Reputation: 1580

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.

Upvotes: 2

Related Questions