我是 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);
}
}
我的 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/