REACTJS:如何知道 Promise 中的方法是否失败?

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

我承诺我的组件中的 WASM 模块对象就是这样调用的

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

这个 myMethod 是一个简单的 cpp 函数。通过注释掉这个方法,我模拟了这个方法是不可访问的,并且在控制台中我从我的 cpp 函数中得到了日志。我怎样才能捕捉到这个失败的方法事件?我想在加载时显示加载栏,在加载失败时显示失败消息

注意:我尝试使用 .catch() 但内部有一个警报,因为错误未定义。

更新:我正在尝试使用带有布尔标志的 react tostify,但是 tast.error 是在状态改变后调用的,而不是在抛出错误后立即调用(请注意我对catch 在 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>
);
 }
  }

您可以添加一个 catch 块来获取 promise 抛出的错误:

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

尝试使用这种语法:

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

我通过使用新的状态设置触发它来解决。