我是 JS 的“异步/等待”方面的新手,我正在尝试了解它是如何工作的。
我得到的错误是以下代码的第 10 行。我创建了一个 firestore 数据库,并试图从 Collection 'rooms' 中侦听并获取某个文档。我正在尝试从文档“joiner”获取数据并使用该数据更新其他元素的 innerHTML。
// References and Variables
const db = firebase.firestore();
const roomRef = await db.collection('rooms');
const remoteNameDOM = document.getElementById('remoteName');
const chatNameDOM = document.getElementById('title');
let remoteUser;
// Snapshot Listener
roomRef.onSnapshot(snapshot => {
snapshot.docChanges().forEach(async change => {
if (roomId != null){
if (role == "creator"){
const usersInfo = await roomRef.doc(roomId).collection('userInfo');
usersInfo.doc('joiner').get().then(async (doc) => {
remoteUser = await doc.data().joinerName;
remoteNameDOM.innerHTML = `${remoteUser} (Other)`;
chatNameDOM.innerHTML = `Chatting with ${remoteUser}`;
})
}
}
})
})
})
但是,我收到错误:
Uncaught (in promise) TypeError: Cannot read property 'joinerName' of undefined
同样,如果我将第 10-12 行更改为:
remoteUser = await doc.data();
remoteNameDOM.innerHTML = `${remoteUser.joinerName} (Other)`;
chatNameDOM.innerHTML = `Chatting with ${remoteUser.joinerName}`;
我遇到了同样的错误。
我目前的理解是 await 将在继续之前等待行/函数完成,因此在尝试调用它之前 remoteUser 不应为 null。我会提到有时代码运行良好,并且 DOM 元素更新并且没有控制台错误。
我的问题:我是否错误地考虑了 async/await 调用?这不是我应该从 Firestore 获取文件的方式吗?最重要的是,为什么它似乎只是有时有效?
答案 0 :(得分:1)
这里有几个错误:
请尝试以下代码:
const db = firebase.firestore();
const roomRef = db.collection('rooms');
const remoteNameDOM = document.getElementById('remoteName');
const chatNameDOM = document.getElementById('title');
let remoteUser;
// Snapshot Listener
roomRef.onSnapshot(async (snapshot) => {
for (const change of snapshot.docChanges()) {
if (roomId != null){
if (role == "creator"){
const usersInfo = roomRef.doc(roomId).collection('userInfo').doc("joiner");
usersInfo.doc('joiner').get().then(async (doc) => {
remoteUser = doc.data().joinerName;
remoteNameDOM.innerHTML = `${remoteUser} (Other)`;
chatNameDOM.innerHTML = `Chatting with ${remoteUser}`;
})
}
}
}
})
答案 1 :(得分:1)
您正在混合使用 async/await
和 then()
,这是不推荐的。我在下面提出了一个基于 Promise.all()
的解决方案,它有助于理解代码中涉及的不同数组。您可以按照@Dharmaraj 的建议使用 async/await
和 for-of
循环对其进行调整。
roomRef.onSnapshot((snapshot) => {
// snapshot.docChanges() Returns an array of the documents changes since the last snapshot.
// you may check the type of the change. I guess you maybe don’t want to treat deletions
const promises = [];
snapshot.docChanges().forEach(docChange => {
// No need to use a roomId, you get the doc via docChange.doc
// see https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentChange
if (role == "creator") { // It is not clear from where you get the value of role...
const joinerRef = docChange.doc.collection('userInfo').doc('joiner');
promises.push(joinerRef.get());
}
});
Promise.all(promises)
.then(docSnapshotArray => {
// docSnapshotArray is an Array of all the docSnapshots
// corresponding to all the joiner docs corresponding to all
// the rooms that changed when the listener was triggered
docSnapshotArray.forEach(docSnapshot => {
remoteUser = docSnapshot.data().joinerName;
remoteNameDOM.innerHTML = `${remoteUser} (Other)`;
chatNameDOM.innerHTML = `Chatting with ${remoteUser}`;
})
});
});
然而,我不清楚的是你如何区分“第一个”snapshot
(即roomRef.onSnapshot((snapshot) => {...}))
)的不同元素。如果有几个 rooms
更改,snapshot.docChanges()
数组将包含多个更改,最后,您将覆盖中的 remoteNameDOM
和 chatNameDOM
元素最后一个循环。
或者您预先知道这个“第一个”snapshot
将始终包含一个文档(因为您的应用程序的架构),然后您可以通过按如下方式处理第一个和唯一元素来简化代码:
roomRef.onSnapshot((snapshot) => {
const roomDoc = snapshot.docChanges()[0];
// ...
});