Search code examples
javascriptes6-promise

How do I pass a context into a Javascript promise


I will be the first to admit, I don't always get JS Promises. So if this is a stupid question I apologize in advance. =) Given the code below, I need to set a property in the class that contains this function (i.e. I need to call "this" within the fullfullment methods and have it refer back to the class.

I saw a few things that related to setting context, but they also required closures (()=>{...code..}) which don't work so well in Internet Explorer. And we can hate on that browser all we want but at the end of the day its a requirement that this code works in IE.

So my question today is, how do I get a reference to this passed into the methods below?

var result = this.saveChanges();

return Promise.resolve(result).then(function (value) {
    return value.HasError === false;
}, function (value) {
   if (value && value.responseJSON) {
       return value.responseJSON.HasError === false;
   }
   return false;
});

Your assistance is appreciated immeasurably.


Solution

  • You can declare a variable that references this and use that in the function.

    var self = this;
    var result = this.saveChanges();
    
    return Promise.resolve(result).then(function (value) {
        self.someProperty = true;
        return value.HasError === false;
    }, function (value) {
       if (value && value.responseJSON) {
           return value.responseJSON.HasError === false;
       }
       return false;
    });