【问题标题】:Convert A Firebase Method To Async Await将 Firebase 方法转换为异步等待
【发布时间】:2019-08-11 09:29:13
【问题描述】:

我有这个使用电子邮件和密码创建 firebase 用户的 firebase 方法

async register(name, email, password,type) {
    let id;
    const createUser = this.functions.httpsCallable('createUser');

    return await this.auth.createUserWithEmailAndPassword({email,password })
      .then((newUser)=>{
        id = newUser.user.uid;
        newUser.user.updateProfile({
          displayName: name
        })
      })
      .then(()=>{
        createUser({
          id:id,
          name:name,
          email:email,
          type:type
        })
      })
  }

它还使用获取用户详细信息和用户类型的云函数将用户添加到 Firestore 集合。

我有 3 个承诺(

  1. createUserWithEmail...()
  2. updateUserProfile()1
  3. createUser()

) 它们相互依赖。如何在一个功能中使用它们?

NB:由于用户类型字段,无法使用functions.auth.user().onCreate() 方法

如何在不使用 .then() 的情况下编写此方法? 一些用户没有出现在数据库中

【问题讨论】:

  • 如果我没听错的话,有些用户不在数据库中,所以它没有输入.then 子句,这就是问题所在。如果我的描述是正确的,那么解决方案是使用.catch 子句,它将进入一个被拒绝的承诺。如果代码不会进入then 子句,则意味着承诺被拒绝,请使用.catch(reason) 处理它。此外,在您的代码中,您将 aync-await 语法与本机承诺混合在一起。 await 暂停函数的执行,直到 promise 被解决或拒绝。如果你使用await,你甚至不需要.then
  • updateProfile 之后(总是)调用createUser 似乎很奇怪——这两个函数都是异步的并且它们都返回一个Promise 吗?

标签: javascript firebase google-cloud-firestore firebase-authentication google-cloud-functions


【解决方案1】:

要删除.then,只需使用await“更好”

async register(name, email, password,type) {
    let id;
    const createUser = this.functions.httpsCallable('createUser');

    const newUser = await this.auth.createUserWithEmailAndPassword({email,password });
    id = newUser.user.uid;
    // assuming the next two functions are asynchrnous AND return a promise
    // if not, just remove await
    await newUser.user.updateProfile({displayName: name});
    await createUser({
        id:id,
        name:name,
        email:email,
        type:type
    });
}

【讨论】:

  • 谢谢...如何添加故障保险以防止其中一个承诺并拒绝所有承诺?
  • 你可以在 try-catch 中包装 awaits
  • 如果您需要故障保险,我会坚持使用.then 并在承诺链的末尾添加一个 .catch 。它会更具可读性,并且 try-catch 会将被拒绝的承诺捕获为“未处理的承诺拒绝”错误,并且您将失去承诺拒绝的原始“原因”。此外,单个 catch 就足够了,因为如果出现在承诺链之后 - 单个 .catch 将处理所有拒绝。
  • @Dennis 我想你的意思是其中一个承诺失败然后全部拒绝?如果是这样,请将所有Promises 包装在一个Promise 中(register 函数返回一个Promise),然后对于每个Promise 使用.then().catch() 并在catch bloc reject() 中包装@ 987654335@.
  • 谢谢你 最后一个问题:return 语句将如何影响方法,我应该将它放在哪里?
猜你喜欢
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 2021-05-17
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多