javascript accumulate():按顺序执行promises或promise-returns函数数组,并使用给定的累加器减少结果

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript accumulate():按顺序执行promises或promise-returns函数数组,并使用给定的累加器减少结果相关的知识,希望对你有一定的参考价值。

const waterfall = require('promise.waterfall')
const Bluebird = require('bluebird')
const _ = require('lodash')

// an array of 10ms functions with different return values
const functions = [
  () => Bluebird.delay(10, 'a'),
  () => Bluebird.delay(10, 'b'),
  () => Bluebird.delay(10, 'c')
]

/** Executes an array of promises or promise-returning functions serially and reduces thes results with the given accumulator */
function promiseReduce(functionsOrPromises, acculumator, start) {
  return waterfall(functionsOrPromises.map((o, i) => {
    const p = typeof o === 'function' ? o() : o
    return acc => p.then(result => acculumator(i === 0 ? start : acc, result))
  }))
}

/** Executes an array of promises or promise-returning functions serially and returns an array of the results. */
function accumulate(functions) {
  return promiseReduce(functions, _.concat, [])
}

accumulate(functions)
  .then(console.log)
  .catch(console.error)


// can be done more directly, albeit a little more complex
functions.reduce((accPromise, f) =>
  f().then(result =>
    accPromise.then(acc => acc.concat(result))
  ), Promise.resolve([])
)
  .then(console.log)
  .catch(console.error)

以上是关于javascript accumulate():按顺序执行promises或promise-returns函数数组,并使用给定的累加器减少结果的主要内容,如果未能解决你的问题,请参考以下文章

Accumulator

Spark Accumulators

Spark Accumulators

Spark(Accumulator)陷阱及解决办法

ImportError: cannot import name accumulate:如何在Python2中实现itertools的accumulate()?

如何在 itertools.accumulate 中使用初始参数?