【发布时间】: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