我正在使用 firebase 身份驗證呼叫登錄函式并檢查自定義用戶宣告。如果不是,則拋出例外。我無法在呼叫者函式中捕獲例外。我可以知道為什么嗎?
const handleLogin = async (data) => {
console.log(data);
setIsSubmitting(true);
auth
.login(data.email, data.password)
.then((res) => {
navigate(from, { replace: true });
})
.catch((error) => {
console.log(error.message);
const message = auth.mapAuthCodeToMessage(error.code);
setLoginError(message ?? error.message);
})
.finally(() => {
mounted.current && setIsSubmitting(false);
});
};
firebase 身份驗證
async function login(email, password) {
return signInWithEmailAndPassword(auth, email, password).then(
async function (res) {
const currentUser = getAuth().currentUser;
if (currentUser) {
currentUser.getIdTokenResult().then(async function (idTokenResult) {
if (idTokenResult.claims.role == "ADMIN") {
await signIn(idTokenResult.token);
} else {
throw new Error("You role is not authorised!");
}
});
}
}
);
}
uj5u.com熱心網友回復:
因為你沒有在這里回傳承諾:
async function login(email, password) {
return signInWithEmailAndPassword(auth, email, password).then(
async function (res) {
const currentUser = getAuth().currentUser;
if (currentUser) {
currentUser.getIdTokenResult().then(async function (idTokenResult) { // ***
if (idTokenResult.claims.role == "ADMIN") { // ***
await signIn(idTokenResult.token); // ***
} else { // ***
throw new Error("You role is not authorised!"); // ***
} // ***
}); // ***
}
}
);
}
您需要回傳該承諾,以便呼叫者知道拒絕。
但是還有一個更根本的問題:你沒有利用你正在使用async函式的事實。沒有任何功能的async功能沒有意義await。一般來說,不要將async函式與顯式的 Promise 回呼混合使用,這樣很容易犯錯誤,比如不回傳 Promise。相反,使用await.
這是使用這些函式的翻譯await(注意:它可能并不完美,它旨在引導您朝著正確的方向前進,但我自然無法運行它,也不知道您的背景關系,因此根據需要進行調整):
const handleLogin = async (data) => {
console.log(data);
setIsSubmitting(true);
try {
await auth.login(data.email, data.password);
navigate(from, { replace: true });
} catch (error) {
console.log(error.message);
const message = auth.mapAuthCodeToMessage(error.code);
setLoginError(message ?? error.message);
} finally {
if (mounted.current) {
setIsSubmitting(false);
}
}
};
async function login(email, password) {
const res = await signInWithEmailAndPassword(auth, email, password);
const currentUser = getAuth().currentUser;
if (currentUser) {
const idTokenResult = await currentUser.getIdTokenResult();
if (idTokenResult.claims.role == "ADMIN") {
await signIn(idTokenResult.token);
} else {
throw new Error("You role is not authorised!");
}
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475017.html
標籤:javascript 反应
上一篇:如何優化大陣列比較
下一篇:如何從外部源獲取資料型別
