在抛出结果firestore之前,请等待回调运行



Im使用react native、Expo和firebase firestore我有表格

产品

  • id
  • 名称

项目

  • id
  • productId
  • 到期日期

我想得到所有的产品和产品的数量。代码为:

export const getProducts = (callback) => {
const db = firebase.firestore();
let products = [];
db.collection('products').get().then((productsSnapshot) => {
productsSnapshot.forEach((_product, index, array) => {
let product = _product.data()
product.id = _product.id;
getItems(product._id, (items, error) => {
product.count = items.length;
products.push(product);
});
});
callback(products, null);
...
export const getItems = (productId, callback) => {
const db = firebase.firestore();
let items = [];
db.collection('items').where('productId', '==', productId).get()
.then((itemsSnapshot) => {
itemsSnapshot.forEach((_item) => {
let item = _item.data();
item.id = _item.id;
items.push(item);
});
callback(items, null);
...

我遇到的问题是getItems上的回调在之后运行,.count从未获得值。

我尝试了异步等待,但我不知道如何使用它,并在使用firestore时抛出了错误。使用回调是个坏主意吗?应该怎么做?

您可以用promise包围它,并将回调放在then中。像这样的。。。

new Promise((resolve, reject) => {
db.collection('products').get().then((productsSnapshot) => {
productsSnapshot.forEach((_product, index, array) => {
let product = _product.data()
product.id = _product.id;
getItems(product._id, (items, error) => {
product.count = items.length;
products.push(product);
});
});
resolve();
});
}).then(function () {
callback(products, null);
});

最新更新