【发布时间】:2021-04-10 01:03:06
【问题描述】:
我们如何从调用它的异步等待函数中捕获错误?
例如,我有一个 React 组件,它调用从另一个模块导入的异步等待函数。当我在该函数中使用 Promise.reject("An unknown has occurred"); 时,在我的 React 组件中为什么我不能在 asyncAwaitFunction.catch((e)=>console.log(e)) 中得到错误?
我什至尝试过throw "An unknown occured",但它似乎不起作用。
反应组件
const handleSubmit = async (e) => {
e.preventDefault();
add(formData, code)
.then(() => router.push("/dashboard/manage"))
.catch((e) => setError(e)); //I want error to be catched here
};
functions.js
export const addUser = async (details, code) => {
const isExist = await isUser(code);
if (!isExist) {
const add = db.batch(); //firebase batch write
add.set(userID(code), details); //Add details to databse
add.commit()
.catch((e)=> {
console.log(e); // error occurs confirmed
Promise.reject("Unknown error occurred"); //this does't get catched in component.
});
} else {
Promise.reject("Already Exists!");
}
};
【问题讨论】:
-
await add.commit(); -
this works...对此表示怀疑。你想返回或者抛出那个被拒绝的 Promise(或者直接抛出一个错误) -
我可能对那条线有误,之前我使用了以前可以工作的
throw。不确定Promise.reject
标签: javascript reactjs asynchronous async-await es6-promise