javascript - react : How to know if a method fails inside a Promise?

标签 javascript reactjs promise es6-promise emscripten

我有一个 promise ,我的组件中的 WASM 模块对象就是这样调用的

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

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

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

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

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

关于javascript - react : How to know if a method fails inside a Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67846490/

相关文章:

node.js - 前端(React)如何与后端(Express)交互?

javascript - 如何摆脱 React 应用程序中的 "Functions are not valid as a React child"警告

javascript - Dojo JsonRest Promise -- 异步调用的顺序

javascript - 哪个 MEAN 生成器 - javascript

javascript - 如何显示使用 jquery 动态检查的字段数量

node.js - 将react-scripts版本从3.4.0更新到5.0.0导致类型错误: Cannot read properties of undefined (reading 'getStackAddendum' )

node.js - 非法参数异常请求包含无法识别的参数: [mapping] - ElasticSearch Index Creation

javascript - 将 JS Promise 值赋给变量

javascript - 如何 : Produce mongoDB query string for the fields dynamically from a javascript app

javascript - 如果 jquery 加载失败,如何停止进一步的 javascript 调用?