代码之家  ›  专栏  ›  技术社区  ›  Simon

javascript-等待在错误的时间触发

  •  1
  • Simon  · 技术社区  · 8 年前

    我是新来的 async await ,我希望有人能帮我。

    我有个函数调用 register 在这个函数中,我注册了一个用户,然后将一些关于他们的数据发送到服务器,这样就可以建立一个“用户配置文件”。

    问题是我还有一个函数 login 这也是异步的,并重定向用户 一旦 他们注册了。意思是“用户配置文件”数据永远不会被发送。

    这是我的 注册 功能:

    async register(user: User) {
        try {
          const result = await this.afAuth.auth.createUserWithEmailAndPassword(user.email, user.password);
          await this.afAuth.auth.currentUser.updateProfile({
            displayName: user.displayName,
            photoURL: ""
          }).then(() => {
            let currentUser = result;
            let date = new Date().getTime();
            let userData = {
              email: currentUser.email,
              displayName: currentUser.displayName,
              uid: currentUser.uid,
              created: date,
            }
            this.database.list('users').set(userData.uid, userData).then(() => {
                return;
            }); //I want to continue after this line is called. 
        return; 
          }, function(error) {
            console.log(error)
          });
        } catch(e) {
          console.log(e);
        }
      }
    

    是我的 等待 在错误的位置?我想要 登录 一旦数据被调用 .set

    你知道我做错了什么吗…我非常感谢你的帮助。谢谢!

    2 回复  |  直到 8 年前
        1
  •  2
  •   user3210641    8 年前

    使用要点 async / await 你不需要处理 then() catch() .

    async function register(user: User) {
      try {
        const result = await this.afAuth.auth.createUserWithEmailAndPassword(user.email, user.password);
    
        await this.afAuth.auth.currentUser.updateProfile({
          displayName: user.displayName,
          photoURL: ""
        });
    
        let currentUser = result;
        let date = new Date().getTime();
        let userData = {
          email: currentUser.email,
          displayName: currentUser.displayName,
          uid: currentUser.uid,
          created: date,
        };
    
        await this.database.list('users').set(userData.uid, userData)
    
        // Do something after everything above is executed
    
        return; 
      } catch(e) {
        console.log(e);
      }
    };
    
        2
  •  0
  •   Josh    8 年前

    等待让你等待一个承诺。异步等待的最大好处之一是不必使用 then 语法或任何明确的承诺。不知道你为什么要混合风格。在等待声明之后“做更多的事情”是非常简单的。

    这是一些伪代码。我去掉了try-catch,因为您的整个函数都在其中,这使它变得毫无意义。此外,如果任何承诺被拒绝,它将被转化为一个例外。如果一个例外发生在一个承诺中,它会被转化为拒绝,然后转化为一个例外。承诺之外的其他例外是普通的旧例外。

    我冒昧地在您的问题中添加了typescript标记,因为您发布了typescript语法。 typescript不是javascript .

    async register(user: User) {
      const result = await createUser(...);
      await updateProfile(...);
      const userData = buildUserData(...);
      await setUserData(database, userData);
      console.log('more stuff after setUserData');
    }
    
    推荐文章