【问题标题】:working with array of promises that have promises inside使用包含承诺的一系列承诺
【发布时间】:2018-10-03 02:28:15
【问题描述】:

我正在执行以下代码:

let promises = []
querySnapshot.forEach(function (doc) {
  promises.push(
    promiseFunction()
    .then((postCounters) => {
      promiseFunction2()
        .then((myRate) => {
        console.log('save array with postCounters AND myRate data')
      })
    })
  )
})
Promise.all(promises).then(() => {
  console.log('the array with postCounters AND myRate data')
})

事情越来越不对劲了。返回的 Promise.all 不会等到 promiseFunction2 运行,所以第二个函数不起作用,我没有在我的数组中获取 promiseFunction2 数据,只是第一个。

我认为正在发生的事情是:Promise.all 在所有 promiseFunction 运行后得到,但它不会等到第二个函数,我想在得到所有承诺之前等待两者都完成,我应该使用两个 Promise 。全部???

我对 Promise.all 的语法不是很熟悉,我只是使用 promiseFunction().then() 方法

(使我的代码保持一致以良好扩展的事件)

【问题讨论】:

    标签: javascript arrays promise


    【解决方案1】:

    您应该使用map 将一个数组转换为另一个数组。问题是您没有返回从 promiseFunction2 生成的承诺链:

    const promises = querySnapshot.map((doc) => (
      promiseFunction()
        .then((postCounters) => (
          promiseFunction2()
            .then((myRate) => {
            console.log('save array with postCounters AND myRate data')
          })
        ))
    ));
    Promise.all(promises).then(() => {
      console.log('the array with postCounters AND myRate data')
    });
    

    或者,为了减少压痕噪音,使用async/await

    const promises = querySnapshot.map(async (doc) => {
      const postCounters = await promiseFunction();
      const myRate = await promiseFunction2();
      // do stuff with myRate
      console.log('save array with postCounters AND myRate data')
      // async functions automatically return promises that resolve when the block finishes
    });
    Promise.all(promises).then(() => {
      console.log('the array with postCounters AND myRate data')
    })
    

    【讨论】:

      【解决方案2】:

      看看这是否有帮助。

        let promises = []
        querySnapshot.forEach(function (doc) {
          promises.push(
            promiseFunction()
              .then((postCounters) => {
                return promiseFunction2();
              })
          )
        })
        Promise.all(promises).then((values) => {
          console.log(values);
        })
      

      【讨论】:

        【解决方案3】:

        你为什么不用这样的promise?!

        let promises = [],
            promiseArr = [];
        querySnapshot.forEach(function (doc) {
            promises.push(
                promiseFunction()
            );
        });
        Promise.all(promises).then((res) => {
            res.forEach(itm => {
                promiseArr.push(
                    promiseFunction2()
                );
            });
        
        
            Promise.all(promiseArr).then((res) => {
                console.log('save array with postCounters AND myRate data');
            });
        
        });
        

        【讨论】:

        • 我想将两个结果合并到一个对象中。 promiseFunction() 将返回 X、Y 字段,promieseFunction2() 将返回 Z。它们中的每一个都必须合并到具有 X、Y、Z 字段的对象数组中,它们必须按顺序进行管理。如果我分别解决它们,我将得到两个分离的数组,我将不得不制作额外的第三个函数将它们合并为一个。如果我决定在数组中添加更多信息,情况会变得更糟
        • 您可以在两个单独的promise.all 完成后将两个结果合并为一个对象,在此之前您没有第二个结果
        • 如果你想异步,我认为你必须编写第三个函数。或者同步进行。
        • 我的结构是:querySnapshot.forEach(function (doc) { promiseFunction() .then((postCounters) => { promiseFunction2().then((myRate) => { posts.push({ a: doc, b: postCounters c: myRate }) }) }) 我很困惑,因为 myRate 和 postCounters 将是单独的数组(我认为)
        • 将第一个结果数组存储在一个变量中(如果您需要全局)。在myRates 实现的第二个承诺中,创建你的最后一个对象。
        【解决方案4】:

        这样使用

        let addQueue = q();
        
        for (let i = 0; i < querySnapshot.length; i++){
         addQueue = addQueue.then(promisFunction.bind(null, querySnapshot[i]))
                                .then(function (r) {
                                    console.log('OK: ', r);
                                })
        }
        
        function promisFunction(doc){
        let deferred = q.defer();
        
        promisFunction2().then((postCounters) =>{
        and function for myRate 
        deferred.resolve({ a: doc, b: postCounters c: myRate }) }
        })
        return deferred.promise//
        }
        
        
         addQueue.then(function (result) {
                            console.log('your result is here');
                        })
        

        【讨论】:

          【解决方案5】:

          在您的示例中,您没有说明为什么promiseFunction2 需要等待promiseFunction。这两个函数都没有返回一些东西,所以不清楚你声称缺少什么值。

          如果promiseFunction2 需要在promiseFunction 之后运行,那么您可以这样做:

          let promises = [];
          querySnapshot.forEach(function (doc) {
            promises.push(
              promiseFunction()
              .then((postCounters) => {
                return promiseFunction2()//missing return here
                .then((myRate) => {
                    console.log('save array with postCounters AND myRate data');
                    return [postCounters,myRate];//missing return here
                })
              })
            );
          })
          

          如果您不需要等待promiseFunction 完成即可开始promiseFunction2,那么您可以这样做:

          let promises = [];
          querySnapshot.forEach(function (doc) {
            promises.push(
              Promise.all(
                promiseFunction(),
                promiseFunction2()
              )
            );
          })
          

          在这两种情况下,结果都是数组数组:

          Promise.all(promises)
          .then(
            function(results){
              results.forEach(
                function(result){
                  console.log("postCounters:",result[0]);
                  console.log("myRate:",result[1]);
                }
              )
            }
          )
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-03-18
            • 2016-09-02
            • 1970-01-01
            • 1970-01-01
            • 2013-10-23
            • 2016-07-27
            • 2017-06-03
            • 2015-10-06
            相关资源
            最近更新 更多