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

标签 javascript typescript async-await

我是 asyncawait 的新手,我希望有人能帮助我。

我有一个函数调用 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);
    }
  }

我的 await 是在错误的位置吗?我希望在数据为 .set...

时调用 login 函数

任何想法我做错了什么..我真的很感激任何帮助。谢谢!

最佳答案

使用要点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);
  }
};

关于Javascript - 等待在错误的时间触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50892991/

相关文章:

c# - HttpClient.SendAsync 不等待/锁定执行

javascript - React 速记条件输出错误数据

javascript - 如何使函数 add 在 javascript 中工作 - console.log(add(2)(3)(4))//9 而不使用 valueof 或 toString

javascript - 如何在 Angular 2 Typescript 中为 FormBuilder 对象设置值

javascript - 在 JSConfig.json 文件中看到未知的 typescript 错误

angular - Ionic 4 中的动态进度条?

javascript - Facebook 用户界面发送

javascript - 未找到 404 NotFoundError : Not Found Node JS and Express

c# - 我可以指定在 await continuation 完成后我希望保留哪些变量吗?

c# - 用于单元测试的模拟周期性计时器