Javascript-在错误的时间等待触发
我对Javascript-在错误的时间等待触发,javascript,typescript,async-await,Javascript,Typescript,Async Await,我对async和wait非常陌生,希望有人能帮我 我有一个函数调用register,在该函数中我注册了一个用户,然后将有关用户的一些数据发送到服务器以构建一个“用户配置文件” 我遇到的问题是,我还有一个名为login的函数,它也是异步的,并且在用户注册后立即重定向用户。。这意味着“用户配置文件”数据永远不会被发送 这是我的寄存器功能: async register(user: User) { try { const result = await this.afAuth.aut
async
和wait
非常陌生,希望有人能帮我
我有一个函数调用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);
}
}
我的wait
是否位于错误的位置?我想在数据被设置后调用登录
函数
你知道我做错了什么吗。。我真的很感激任何帮助。谢谢 使用的意义在于,您不必处理then()
或catch()
等待让你等待承诺。async await的最大好处之一是不必使用then
语法或任何明确的承诺。不知道你为什么混合风格。在等待声明之后“做更多的事情”是非常简单的
下面是一些伪代码。我去掉了try-catch,因为您的整个函数都在其中,这使得它毫无意义。此外,如果任何承诺被拒绝,它将被转换为例外。如果一个例外发生在一个承诺中,它被转化为拒绝,然后转化为例外。承诺之外的其他例外都是普通的旧例外
我冒昧地在您的问题中添加了TypeScript标记,因为您发布了TypeScript语法。TypeScript不是Javascript
如果set
返回承诺,则在该行中添加返回语句。同时在以this.afAuth.auth.currentUser.updateProfile开头的行中添加return
,您还需要等待this.afAuth.auth.currentUser.updateProfile
@JaromandaX我试过了。它不工作。@JaromandaX我更新了上面的代码。@marainesparnisari我更新了上面的代码,但仍然不工作。。。
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);
}
};
async register(user: User) {
const result = await createUser(...);
await updateProfile(...);
const userData = buildUserData(...);
await setUserData(database, userData);
console.log('more stuff after setUserData');
}