React Native 如何优化Firestore查询?

cnjp1d6j  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(145)

我有一个集合,它有两个子集合,我像这样取它

for (let doc of data.docs) {
  const finalPurchase = {
    ...(doc.data() as Purchase),
    classification: [],
    history: [],
  };
  finalPurchase.classification = await getClassificationDocs(cnpj, doc.id);
  finalPurchase.manufacturers = await getManufacturersDocs(cnpj, doc.id);
  finalDocs.push(finalPurchase);
}

子集合查询是这样的

const getManufacturersDocs = async (
  cnpj: string,
  parentDocId: string
): Promise<Manufacturer[]> => {
  const manufacturersRef = collection(
    db,
    "company",
    cnpj,
    "purchases",
    parentDocId,
    "manufacturers"
  );

  const manufacturersDocs = await getDocs(manufacturersRef);

  return manufacturersDocs.docs.map((item) => {
    return { ...(item.data() as Manufacturer) };
  });
};

虽然它的工作,它需要很长的时间才能得到一切。有什么方法可以优化它吗?

7vux5j2d

7vux5j2d1#

您可以尝试以下请求:您可以使用Promise.all()并发地执行请求,而不是向Firestore发出多个单独的请求。这可以显著减少获取数据所需的总时间。
大概是这样的:

const promises = [];

for (let doc of data.docs) {
  const finalPurchase = {
    ...(doc.data() as Purchase),
    classification: [],
    history: [],
  };

  const classificationPromise = getClassificationDocs(cnpj, doc.id);
  const manufacturersPromise = getManufacturersDocs(cnpj, doc.id);

  promises.push(
    classificationPromise.then((classification) => {
      finalPurchase.classification = classification;
    })
  );

  promises.push(
    manufacturersPromise.then((manufacturers) => {
      finalPurchase.manufacturers = manufacturers;
    })
  );

  finalDocs.push(finalPurchase);
}

await Promise.all(promises);

相关问题