0

Is there a correct or "better" way to handle this is JavaScript classes with-in Promises (or Callbacks even)

Currently I have just getting around this by doing this

 var self = this;

But this feels 'hackey' to me.

Ignore most of the code below, it's just to get my point across.

 class thing {
  drawthing(thing) {
  console.log(thing); 
  }

  updatethings(thing) {
      var self = this;  //a better way to do this
      return new Promise(function (resolve) {
           setTimeout(function(){
               self.drawthing(thing);
               return resolve(thing);
           },2000);
      });
  }
}

var t = new thing();
t.updatethings('hello').then(console.log);
Christopher Chase
  • 2,840
  • 6
  • 36
  • 57

3 Answers3

1

Arrow functions will do this for you. Check out some explanations and examples here.

Here's a corrected snippet:

class thing {
  drawthing(thing) {
      console.log(thing);   
  }

  updatethings(thing) {
          // arrow func
          return new Promise((resolve) => {
               // another arrow func
               setTimeout(() => {
                   // Because of arrow function scoping, `this` passes through.
                   this.drawthing(thing);
                   return resolve(thing);
               },2000);
          });
      }
}

var t = new thing();
t.updatethings('hello').then(console.log);
pxljoy
  • 475
  • 1
  • 4
  • 15
  • This feels like it's missing some valid information that could help people learning like bound functions and static methods – Robert Mennell Jun 26 '18 at 02:00
  • 1
    I have referenced another article on SO that outlines those better than I could, and, no reason to duplicate it here. – pxljoy Jun 26 '18 at 02:01
1

Try using a lambda/arrow function:

updatethings(thing) {
      return new Promise((resolve) => {
           setTimeout(() => {
               this.drawthing(thing);
               return resolve(thing);
           },2000);
      });
  }
0

If your method drawthing() will throw any exception or error then your promise will never get resolved and will eventually throw an exception.

You should also handle reject case in the time of exception like

 updatethings(thing) {
      var self = this;  //a better way to do this
      return new Promise((resolve, reject)=>{
           setTimeout(()=>{
              try{
                self.drawthing(thing);

              }catch(err){ return reject(err);}

              return resolve(thing);

           },2000);
      });
  }

And while calling your method your should also catch the exception.

t.updatethings('hello').then(console.log).catch((err)=> {console.log("handle error")});
deepansh2323
  • 261
  • 1
  • 8