【发布时间】:2019-09-30 20:56:55
【问题描述】:
我在这里有一些代码,我正在使用 firebase auth 将用户登录到 firebase。我在我的 app.js 文件中实例化一个新用户,在该对象上调用 signIn 方法,然后在我的用户类的 signIn 方法中,我是控制台登录来自 firebase auth 的返回凭证。我还将凭证返回给调用它的对象并再次在控制台记录凭证。当我使用 async / await 时,代码会按照我的预期运行:它首先在 signIn 方法中记录凭据,然后在我调用 signIn 之后再次在 app.js 中记录。
但是,当我尝试使用 .then 方法执行此操作时,我的 app.js 文件中的 console.log 在控制台登录 User 类的 signIn 方法之前显示未定义。但是,User 类的 signIn 方法中的控制台日志会返回正确的凭据。
我的问题是:为什么我的 app.js 文件中的控制台日志没有在控制台日志记录之前等待获取凭据?或者至少控制台记录一个承诺?
class User {
constructor(email, password){
this.email = email;
this.password = password;
this.cred;
}
async signUp(){
const cred = await auth.createUserWithEmailAndPassword(this.email, this.password);
return cred;
}
async signIn() {
auth.signInWithEmailAndPassword(this.email,this.password).then(cred=>{
console.log(cred);
return cred;
});
//this async/await code below works as expected
// const cred = await auth.signInWithEmailAndPassword(this.email,this.password);
// console.log(cred);
// return cred;
}
signOut(){
}
}
export default User
// beginning of my app.js file
loginForm && loginForm.addEventListener('submit', async e => {
e.preventDefault();
const user = new User(loginForm.email.value,loginForm.password.value);
//const cred = await user.signIn(); // this async/await code works fine
//console.log(cred);
user.signIn().then(cred => {
console.log(cred); // this console.log fires before the console.log in signIn() and returns undefined
loginForm.reset();
})
});
【问题讨论】:
-
你的
signIn()需要返回里面的Promise。目前它什么也不返回,这就是为什么user.signIn().then()根本不应该工作。 -
因为 signIn 没有返回承诺,所以它不是链的一部分。
标签: javascript firebase asynchronous promise