简体   繁体   English

REACTJS:如何知道方法是否在 Promise 内失败?

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

I have an promise that is the Module object of a WASM in my component called like that我的组件中有一个 promise,它是一个 WASM 的模块 object

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

this myMethod is a simply cpp function.这个 myMethod 是一个简单的 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?通过注释掉这个方法,我模拟了这个方法是不可访问的,并且在控制台中我从我的 cpp function 获取了日志。我怎样才能捕捉到这个失败的方法事件? 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.注意:我尝试了 using.catch() 但里面有一个警报,因为没有定义错误。

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():更新:我正在尝试使用带有 boolean 标志的 react tostify,但是在 state 更改后调用 tast.error,而不是在抛出错误后立即在 catch 中调用(请注意,我的 ZB321DE3BDC299EC807E9F79D 组件内部带有) :

  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>
);
 }
  }

You can add a catch block to get errors thrown by the promise:您可以添加一个catch块来获取 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.我通过使用 state 的新设置触发它来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM