我有一个函数,它返回Promise。
updatePassword(currentPassword: string, newPassword: string): Promise<void> {
return this.fireAuth.currentUser.then((user: firebase.User) => {
if (user) {
const credentials = auth.EmailAuthProvider.credential(user.email, currentPassword)
user.reauthenticateWithCredential(credentials).then(res => {
if (res) {
user.updatePassword(newPassword)
}
}).catch(err => {
throw new Error(err)
})
}
})
}
我在另一个组件里调用它
this.userService.updatePassword(currentPassword, newPassword).then(() => {
console.log('successfully')
}).catch(err => {
console.log('error')
})
但即使当 updatePassword()
return Error,组件中的函数调用仍然是控制台从'then'记录'成功'。在我的情况下,如何正确地抛出一个错误?
你还需要返回你的内部承诺。像这样。
updatePassword(currentPassword: string, newPassword: string): Promise<void> {
return this.fireAuth.currentUser.then((user: firebase.User) => {
if (user) {
const credentials = auth.EmailAuthProvider.credential(user.email, currentPassword)
return user.reauthenticateWithCredential(credentials).then(res => {
if (res) {
user.updatePassword(newPassword)
}
}).catch(err => {
throw new Error(err)
})
}
throw new Error('USER_NOT_FOUND')
})
}
编辑:我还添加了 throw
如若不然 user
作为安全网。
重构你的函数,使用 async
await
而你不需要手动扔任何东西。
你可能希望让这些 return false
是某种 throw
也是。
async updatePassword(currentPassword: string, newPassword: string): Promise<void> {
const user = await this.fireAuth.currentUser;
if(!user) return false;
const credentials = auth.EmailAuthProvider.credential(user.email, currentPassword);
const res = await user.reauthenticateWithCredential(credentials);
if(!res) return false;
user.updatePassword(newPassword);
return true;
}
如果你的 fireAuth
调用失败,则抛出一个 Error
来自 updatePassword
catch
块。
检查所附的工作片段。
let fireAuth = (pass = false) => {
if (pass) return Promise.resolve("passed");
return Promise.reject("failed");
};
function updatePassword(shouldPass = false) {
if (!shouldPass) {
return fireAuth(false)
.then(console.log)
.catch((err) => {
console.log('err in fireauth', err)
throw new Error('OOPS')
});
}
return Promise.resolve("success");
}
let failedResult = updatePassword()
.then()
.catch((err) => console.log("failedresult error", err.toString()));
let successResult = updatePassword(true)
.then((res) => console.log("res is", res))
.catch();