我有一个 firestore 系列,我想退回整个东西,但我目前只退回一件。我的直觉是,因为我的 resolve 函数在 forEach 中,所以它只返回它看到的最后一项,但是当我将它移到 forEach 之外时,我的数据返回未定义
这是我写的:
componentDidMount() {
this.getItemsPromise().then((data) => {
this.setState({ data: data })
});
}
getItemsPromise() {
return new Promise((resolve, reject) => {
this.cancelPromise = reject;
const db = firebase.firestore();
db.collection("items").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
const data = [];
data.push(doc.data())
resolve(data);
});
});
});
}
最佳答案
试试这个。最好不要将 const 用于可编辑数组数据。并且您应该将 resolve 放在 forEach 之外,这样 resolve 就不会在第一个循环中触发。
getItemsPromise() {
return new Promise((resolve, reject) => {
this.cancelPromise = reject;
const db = firebase.firestore();
db.collection("items").get().then(function(querySnapshot) {
let data = [];
querySnapshot.forEach(function(doc) {
data.push(doc.data());
});
resolve(data);
});
});
}
关于javascript - 如何遍历数据集合并返回整个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349308/