[英]Wrapping a Firebase promise in TypeScript
I am trying to convert two functions into more DRY code:我正在尝试将两个函数转换为更多 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);
});
}
I want to create a separate method that wraps up both methods, so I can re-use the same code.我想创建一个单独的方法来包装这两种方法,这样我就可以重用相同的代码。 I am writing a method, and this is what I have so far, and this is the point at which I need to ask this question.
我正在写一个方法,这就是我到目前为止所拥有的,这就是我需要提出这个问题的地方。 I am unsure of how to best combine these methods because I am not familiar with promises.
我不确定如何最好地组合这些方法,因为我不熟悉 promise。 What should I be returning in the resolve() portion of these two promises to make my new method work properly?
我应该在这两个承诺的 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);
});
}
Both functions already return a Promise<UserCredential>
.这两个函数都已经返回
Promise<UserCredential>
。 So, there is no need to wrap them in another Promise.因此,无需将它们包装在另一个 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;
}
NineBerry's answer is correct, and I ended up implementing with: NineBerry 的答案是正确的,我最终实现了:
async useAuth(user: User, action: string) {
if (action === 'signIn')
return await this.db.auth.signInWithEmailAndPassword(user.email, user.pass);
else if (action === 'register')
return await this.db.auth.createUserWithEmailAndPassword(user.email, user.pass);
}
I did it this way!我是这样做的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.