【问题标题】:REACTJS : How to know if a method fails inside a Promise?REACTJS:如何知道 Promise 中的方法是否失败?
【发布时间】:2021-08-23 01:18:27
【问题描述】:

我有一个承诺,它是我的组件中的一个 WASM 的模块对象

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

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

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

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

【问题讨论】:

  • 什么是失败的方法事件?你是在说module.myMethod(); 没有被调用吗?或者 module.myMethod(); is 被调用并抛出 some 错误?你能分享一下你是如何/在哪里使用.catch 块/thenable 的吗?
  • 你可以像docs这样传递解析和拒绝回调函数
  • @DrewReese 是的,该方法被调用,但我想模拟一些连接问题。我想知道如果在 apromise 中失败了这个方法,所有的承诺都会失败,所以我可以使用 .catch()
  • 你需要抛出一个错误或者主动reject一个Promise。我不确定这是否是您正在寻找的,但您也可以尝试制作一个定时的 Promise 高阶函数,如果函数在设定的超时时间内未解析,该函数会自动拒绝。
  • this.fail= true; 不会在反应中导致重新渲染,您需要为此使用状态。同样在您的代码 sn-p 中,还不清楚 componentDidMount 的一部分以及 render 的一部分。最好发布一个完整的class 可以执行的代码。

标签: javascript reactjs promise es6-promise emscripten


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试使用这种语法:

    const myPromise = new Promise((resolve, reject) => {
      const test = true;
      test? 
           resolve(test):  //resolve it return the good value
           reject('Error'); //reject return the error
    });
    
    【解决方案3】:

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

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

    【讨论】:

    • 警报有效,但 toastify 无效!请看我的更新
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2014-10-28
    相关资源
    最近更新 更多