how to implement a promise between two javascript functions?

259 Views Asked by At

I have two functions in my angular application, in the first one I put to true the loader, I show and hide some components of my html and finally I call to another function to make a sucription of data.

  handleClick() {

    if (this.isDisabledSaveButton) { 
      this.setData();
    } else {
      this.emitLoader = true;
      this.showForm();
      this.hideTools();
      this.formSubmit();
    }
  }

at the end of the function this.formSubmit(), after a subscription and different conditions, I set the loader to false and I would like to communicate it to the first function through a Promise

formSubmit() {
     this.loadFooter = false;
     if (this.formSubscription !== undefined) {
      this.formSubscription.unsubscribe();
    }

    // differents conditions....

        

    this.emitLoader = false;
    this.blockButtons();
}

is the first promise I try to implement and for many examples I see I am not able to return the value to the first function in order to make a redirection after successful subscription

handleClick() {

    if (this.isDisabledSaveButton) { 
      this.setData();
    } else {
      this.emitLoader = true;
      this.showForm();
      this.hideTools();
      this.formSubmit();
      let promise = new Promise((resolve, reject) => {
        this.router.navigate(['pages/incineris/conventions']);
      });
      return promise;
    }
  }

How should I relate the two functions to the promise? I want to resolve the promise after this.emitLoader = false in the formSubmit() function. Thank you all for your help

1

There are 1 best solutions below

1
On BEST ANSWER

formSubmit() is performing the asynchronous operation. This represents the "promise" of a result in the future. Here I have created a new Promise object, but usually your network request itself may be returned here, since that library may be returning a promise of its own.

formSubmit() {
  // ...
  return new Promise((resolve, reject) {
    // ...
  });

The handleClick() function waits for the promise to be fulfilled, and uses .then() to proceed on success.

handleClick() {
  // ...
  this.formSubmit().then(() => {
    this.router.navigate(['pages/incineris/conventions']);
  });
}