简体   繁体   中英

Wrapping a Firebase promise in TypeScript

I am trying to convert two functions into more DRY code:

  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. What should I be returning in the resolve() portion of these two promises to make my new method work properly?

  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> . So, there is no need to wrap them in another 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:

  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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM