函数即使通过也不返回true



我似乎无法使此工作,但我希望每次函数执行成功时都返回true,在本例中为"更改密码"。

async function ChangePassword(data) {
const auth = getAuth();
let res = false;
const credential = EmailAuthProvider.credential(
auth.currentUser.email,
data.oldPassword
);
reauthenticateWithCredential(auth.currentUser, credential)
.then(() => {
updatePassword(auth.currentUser, data.password)
.then(() => {
toast.success("Password changed successfully");
res = true;
console.log("res ",res);
})
.catch((error) => {
toast.error(error.message);
});
})
.catch((error) => {
toast.error(error.message);
});
return res;
}

res变量在被其他函数调用时总是导致false,即使我看到toast消息"Password changed successfully"

async function changePassword() {
if (password === "" || confirmPassword === "" || oldPassword === "") {
toast.error("Please fill all the fields");
} else if (password !== confirmPassword) {
toast.error("Passwords do not match");
} else {
let data = { oldPassword, password };
await ChangePassword(data).then((res) => {
if (res === true) {
setChangePasswordModal(false);
setOpen(false);
}
});
}
}

上面代码中的if条件永远不会执行,因为res总是false。我知道它与async await有关,但不知道如何使它工作

async function ChangePassword(data) {
const auth = getAuth();
let res = false;
const credential = EmailAuthProvider.credential(
auth.currentUser.email,
data.oldPassword
);
reauthenticateWithCredential(auth.currentUser, credential)
.then(() => {
updatePassword(auth.currentUser, data.password)
.then(() => {
toast.success("Password changed successfully");
res = true;
console.log("res ",res);
})
.catch((error) => {
toast.error(error.message);
});
})
.catch((error) => {
toast.error(error.message);
});
return res;
}

有很多逻辑错误。

首先,您应该决定是否要使用async及其特性await或经典的Promise.thenable样式。请不要同时使用,这只会混淆你和读者。

让我们放弃异步(因为你甚至不使用await),Promises是可链的,你不(也必须不)嵌套.then块,使用这个代替:

function ChangePassword(data) {
const auth = getAuth();
const credential = EmailAuthProvider.credential(auth.currentUser.email, data.oldPassword);
return reauthenticateWithCredential(auth.currentUser, credential)
.then(() => {
return updatePassword(auth.currentUser, data.password)
})
.then(() => {
toast.success("Password changed successfully");
return true;
})
.catch((error) => {
toast.error(error.message);
return false;
})
}
这里的关键是ChangePassword本身返回一个Promise。*

调用者负责使用.then或将asyncawait结合使用:

ChangePassword({/* data */}).then((result) => {
console.log("ChangePassword done", result)
})
如果您使用async: ,相同的代码看起来要干净得多。
async function ChangePassword(data) {
const auth = getAuth();
const credential = EmailAuthProvider.credential(auth.currentUser.email, data.oldPassword);
try {
await reauthenticateWithCredential(auth.currentUser, credential);
await updatePassword(auth.currentUser, data.password);
toast.success("Password changed successfully");
return true;
} catch (error) {
toast.error(error.message);
return false;
}
}

(如果你想知道它看起来像什么)。

*a函数标记为asyncALWAYS顺便说一下,返回一个承诺。

最新更新