I am in the process of refactoring two functions to make them more concise and efficient:
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 aim to streamline these functions by creating a separate method that encapsulates both functionalities for reusability. I'm currently working on this new method and need advice on how to merge these functions effectively since I'm not well-versed in promises. What should be included in the resolve() section of these two promises to ensure my new method operates correctly?
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);
});
}