首页 > 解决方案 > 如何在从我的承诺/功能返回之前等待 forEach 完成

问题描述

角,火库

我有一个角度函数来从一个 firestore 集合中获取产品,然后我循环该查询的结果以从另一个集合中查找价格。

在从外部承诺和外部函数本身返回之前,我如何才能等到 forEach 的价格完成?

返回的结果包含一个产品数组,但每个产品的价格数组为空。

 const products = await this.billingService.getProducts();
async getProducts() {
    let result = [];
    let product = {};
    return this.db.collection(
      'products',
      ref => { ref
        let query: Query = ref;
          return query.where('active', '==', true)
      })
      .ref
      .get()
      .then(function (querySnapshot) {
        querySnapshot.forEach(async function (doc) {
          product = doc.data();
          product['prices'] = [];

          await doc.ref
            .collection('prices')
            .orderBy('unit_amount')
            .get()
            .then(function (docs) {
              // Prices dropdown
              docs.forEach(function (doc) {
                const priceId = doc.id;
                const priceData = doc.data();
                product['prices'].push(priceData);
              });
            });
        });
        result.push(product);
        return result;
      });
  }

我也尝试过这种方法,但不确定如何访问结果

await this.billingService.getProducts().then(results =>
getProducts() {
      const dbRef =
        this.db.collection(
          'products',
          ref => { ref
            let query: Query = ref; return query.where('active', '==', true)
        });
       const dbPromise = dbRef.ref.get();

      return dbPromise
        .then(function(querySnapshot) {
          let results = [];
          let product = {};
          querySnapshot.forEach(function(doc) {
            let docRef = doc.ref
              .collection('prices')
              .orderBy('unit_amount')
              results.push(docRef.get())
          });
          return Promise.all(results)
        })
        .catch(function(error) {
            console.log("Error getting documents: ", error);
        });
    } 

标签: javascriptgoogle-cloud-firestorepromise

解决方案


根据评论发布为社区 Wiki 答案。

对于这种情况,使用 aforEach()不是正确的选择。正如在这种情况下所阐明的那样forEach()不能与await函数一起正常工作,这样,你的承诺就不能正常工作。考虑到这一点以及您希望按顺序读取数据的事实 - 因为一个查询的结果会影响第二个查询 - 您需要使用正常的for, 来遍历数据和数组。这里的这个具体答案应该可以帮助您处理代码示例。


推荐阅读