[英]Wrapping a Firebase promise in TypeScript
我正在嘗試將兩個函數轉換為更多 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。 我應該在這兩個承諾的 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;
}
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);
}
我是這樣做的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.