繁体   English   中英

在 TypeScript 中包装 Firebase 承诺

[英]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.

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