0

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.

Peter Lange
  • 2,786
  • 2
  • 26
  • 40
  • 1
    `var self = this;` above the `promise` should be accessible in the provided scope. – Mouser Jan 16 '20 at 23:18
  • 2
    FWIW, what you referred to as "closures" appears to be the arrow function syntax, where `this` works indeed differently. In theory every function is a closure in JavaScript. The fact that you are using promises is irrelevant as well. – Felix Kling Jan 16 '20 at 23:20

1 Answers1

0

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;
});
Jacob McGowan
  • 592
  • 4
  • 10