我有一个 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/