我正在尝试将两个函数转换为更多的 DRY 代码:
async registerUser(newUser: User) {
await this.db.auth
.createUserWithEmailAndPassword(newUser.email, newUser.pass)
.then(data => {
this.db.auth.currentUser.getIdToken().then(reply => {
this.http
.post('http://localhost:3000/login', { token: reply })
.toPromise()
.then(response => {
if (response['valid'] === 'true') {
localStorage.setItem('user', JSON.stringify(reply));
this.router.navigate(['dash']);
}
});
});
})
.catch(err => {
console.log('registration failed: ' + err.message);
});
}
async signIn(newUser: User) {
await this.db.auth
.signInWithEmailAndPassword(newUser.email, newUser.pass)
.then(data => {
this.db.auth.currentUser.getIdToken().then(reply => {
this.http
.post('http://localhost:3000/login', { token: reply })
.toPromise()
.then(response => {
if (response['valid'] === 'true') {
localStorage.setItem('user', JSON.stringify(reply));
this.router.navigate(['dash']);
}
});
});
})
.catch(err => {
console.log('signIn failed: ' + err.message);
});
}
我想创建一个单独的方法来包装这两种方法,这样我就可以重复使用相同的代码。我正在写一个方法,这是我目前所拥有的,这就是我需要问这个问题的时候。我不确定如何最好地结合这些方法,因为我不熟悉 promise 。我应该在这两个 promise 的 resolve() 部分中返回什么以使我的新方法正常工作?
async useAuth(user: User, action: string) {
if (action === 'signIn') {
return await new Promise((resolve, reject) => {
this.db.auth.signInWithEmailAndPassword(user.email, user.pass);
});
} else if (action === 'register') {
return await new Promise((resolve, reject) => {
this.db.auth.createUserWithEmailAndPassword(user.email, user.pass);
});
}
最佳答案
两个函数都已经返回一个 Promise<UserCredential>
.因此,无需将它们包装在另一个 Promise 中。
async useAuth(user: User, action: string)
{
let result; // type is UserCredential
if (action === 'signIn')
{
result = await this.db.auth.signInWithEmailAndPassword(user.email, user.pass);
}
else if (action === 'register')
{
result = await this.db.auth.createUserWithEmailAndPassword(user.email, user.pass);
}
else
{
throw "unknown action " + action;
}
return result;
}
关于javascript - 在 TypeScript 中包装 Firebase promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143312/