我使用react-native,Expo和firebase firestore我有 table
products
-
id
-
名字
items
-
id
-
productId
-
expirationDate
我想获得所有产品和产品的数量 . 代码是:
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时抛出错误 . 使用回调是个坏主意吗?应该怎样做?
1 回答
您可以通过承诺包围它,并将回调放入当时 . 这样的东西......