因此,我试图从集合中获取一个文档,使用来自当前用户的id,请求getDoc工作,但是当我试图从导出的函数返回信息时,出现了所有问题,函数被调用,但它在函数返回所需的值之前运行,所以它只获得未定义的信息,我尝试过使用.then()、异步函数,但它根本无法工作。
它位于html <·script type=“模块”“src="./Home.js">调用的主javascript文件上。
window.addEventListener('DOMContentLoaded', async() => {
UserStatus()
const userinfo = await getUserInfo('UniversityStaff');
//.then((userinfo) => {
console.log(userinfo.data())
// const userProfile = userinfo.data();
// let html ='';
// html+=`
// <h5><b>Usuario:</b>${userProfile.userName}</h5>
// <h5><b>Correo institucional:</b>${userProfile.email}</h5>
// <h5><b>Telefono:</b>${userProfile.phone}</h5>
// <h5><b>Departamento:</b>${userProfile.area}</h5>
// <h5><b>Puesto:</b>${userProfile.jobTitle}</h5>
// <h5><b>Horario:</b>${userProfile.workingHours}</h5>`
// userInfo.innerHTML = html;
// })
})
这是javascript文件,它包含来自firebase模块的所有代码。这由./Home.js导入。
export const getUserInfo = (collection) => {
onAuthStateChanged(auth, (user) => {
if (user) {
getDoc(doc(db, collection, user.uid))
.then((doc)=>{
console.log(doc.data())
return doc;
})
}
})
}·这是.then()/await在导出const getUserInfo之前完成的错误
Home.js:14 Uncaught (承诺) TypeError:无法在Home.js:14:30 (匿名)@ Home.js:14上读取未定义的属性(读取“数据”)
·这是来自export请求的数据
firebase.js:112 {area:'',id:‘jX3J5XjwDphlE1rQRxOHyDqMI 2’,电子邮件:'userExaple@gmail.com',电话:'6181690397',userName:'Edmundo‘,…}
发布于 2022-07-19 01:53:25
getUserInfo函数中的顶级代码不返回任何值,因此在调用该函数时使用的await没有意义--就像getDoc回调中的return doc一样。
由于您希望等待异步操作,因此需要返回一个承诺get getUserInfo
export const getUserInfo = (collection) => {
return new Promise((resolve, reject) => {
onAuthStateChanged(auth, (user) => {
if (user) {
getDoc(doc(db, collection, user.uid)).then((doc)=>{
resolve(doc)
})
}
})
})
}因此,此代码返回的Promise只在加载文档后解析,这意味着您的await得到了它所期望的结果。
另请参阅:
https://stackoverflow.com/questions/73030030
复制相似问题