[英]REACTJS : How to know if a method fails inside a Promise?
我的組件中有一個 promise,它是一個 WASM 的模塊 object
this.myPromise.then(async (module: any) => {
module.myMethod();
...other methods and logic
}).catch(alert());
這個 myMethod 是一個簡單的 cpp function。 通過注釋掉這個方法,我模擬了這個方法是不可訪問的,並且在控制台中我從我的 cpp function 獲取了日志。我怎樣才能捕捉到這個失敗的方法事件? 我想在加載時顯示加載欄,並在失敗時顯示失敗消息
注意:我嘗試了 using.catch() 但里面有一個警報,因為沒有定義錯誤。
更新:我正在嘗試使用帶有 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>
);
}
}
您可以添加一個catch
塊來獲取 promise 引發的錯誤:
this.myPromise.then(async (module: any) => {
module.myMethod();
// ...other methods and logic
}).catch(error => {alert(error)});
嘗試使用以下語法:
const myPromise = new Promise((resolve, reject) => {
const test = true;
test?
resolve(test): //resolve it return the good value
reject('Error'); //reject return the error
});
我通過使用 state 的新設置觸發它來解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.