2

I have a simple class

class A{
  constructor(){
   this.loadComponents().then(function(values) {callbackOnLoad();});
  }

  callbackOnLoad(){
  //do some things
  }

  loadComponents(){
    ...
    return Promise.all([p1,p2,p3,p4,p5,p6,p7,p8]);
  }
}

I am unable to call callbackOnLoad after all promises are fulfilled. I know that "this" depends on the caller and so I understand why callbackOnLoad does not work. How can I solve this problem? How do I have to structure/design my code?

user3579222
  • 1,103
  • 11
  • 28
  • 1
    Does this answer solve your problem? https://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises – Cat Mar 07 '19 at 16:03

1 Answers1

2

The proper way to do it would be calling then & catch immediately after Promise.all.

class A{
  constructor() {
    this.loadComponents();
  }

  callbackOnLoad = () => {
    //do some things
  }

  loadComponents = () => {
    return Promise.all([p1,p2,p3,p4,p5,p6,p7,p8]).then((values) => {
      this.callbackOnLoad();
    }).catch((error) => {
      console.log(error);
    });
  }
}
Avanthika
  • 3,984
  • 1
  • 12
  • 19
  • Can you explain the difference between my and your code? Is it just the long arrow function? Whould this also work: constructor(){ this.loadComponents().then((values) =>{callbackOnLoad();}); } – user3579222 Mar 09 '19 at 20:44