REACTJS : How to know if a method fails inside a Promise?

Viewed 116

I have an promise that is the Module object of a WASM in my component called like that

this.myPromise.then(async (module: any) => {
module.myMethod();
 ...other methods and logic
 }).catch(alert());

this myMethod is a simply cpp function. By commenting out this method I have simulated that this method isn´t reacheble and in the console I got the log from my cpp function .How can I catch this failing method event ? I want to display a loading bar while it loads and a failure message when it fails

NOTE: I tried using .catch() but with an alert inside because and error was not defined.

UPDATE: I am trying to use react tostify with a boolean flag but the tast.error is called after the state is changed not in the catch as soon as the error is thrown(note that my promise with the catch is inside the componentDidMount():

  componentDidMount() {
 this.myPromise.then(async (module: any) => {
module.myMethod();
 ...other methods and logic

 }).catch(alert()); .catch((err: any) => {
    console.log(err);
    this.fail= true;

    toast.error("Error occurred!", {
      position: "top-right",
      autoClose: 5000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true,
      progress: undefined,
    });
  });
   }//end of componentDidMount


   ...

   return (
  <React.Fragment>
    {this.fail== true ? (
      <div>
        <ToastContainer />
      </div>
    ) : (
      <React.Fragment>
        other content to show
      </React.Fragment>
    )}
  </React.Fragment>
);
 }
  }
3 Answers

You can add a catch block to get errors thrown by the promise:

this.myPromise.then(async (module: any) => {
module.myMethod();
 // ...other methods and logic
 }).catch(error => {alert(error)});

Try to use this syntax :

const myPromise = new Promise((resolve, reject) => {
  const test = true;
  test? 
       resolve(test):  //resolve it return the good value
       reject('Error'); //reject return the error
});

I resolved by triggering it with a new setting of the state.

Related