How do I make this async foreach loop work with promises?

后端 未结 4 1956
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 03:36

I\'ve already messed around with Promises in it, but I\'m new to them and I just can\'t figure out how to do it properly. At the moment, there\'s no point to the Promise, be

4条回答
  •  忘掉有多难
    2020-12-08 03:47

    I know this is an old question but things have changed a bit recently.

    If you're fine with using external libraries, the Bluebird promise library has a pretty good implementation for this: Promise.each.

    E.g.

    function helperFunc(zippyarray) {
      return Promise.each(zippyarray, zippy => {
        return someOperationThatReturnAPromise(zippy)
          .then((singleResult) => {
            // do something with the operation result if needed
          })
      }).then((originalArray) => {
        // this happens only after the whole array is processed
        // (result is the original array here)
        return Promise.resolve(originalArray)
      })
    }
    

提交回复
热议问题