我正在寻找一些算法建议。假设您要执行以下操作:

operation.getAnimal('zebra')
  .then(animal => {
    return operation.doSomethingWithAnimal(animal)
  })


但是,您需要对多种不同的动物执行此操作,而不是一次只执行一次。

let animals = ['zebra', 'dog', 'cat', 'fish', 'bird']

Promise.map(animals).then(animalName => {
  return operation.getAnimal(animalName)
    .then(animal => {
      return operation.doSomethingWithAnimal(animal)
    })
})


或者您可以执行以下操作:

function props (items, promise) {
  let results = {}
  _.each(items, item => {
    results[item] = promise(item)
  })
  return results
}

Promise.props(props(animals, option.getAnimal))
  .then(gottenAnimals => {
    return Promise.props(props(gottenAnimals, options.doSomethingWithAnimal))
  })


第一个例子是让动物做点什么,然后,
第二个示例将使所有动物然后奔跑对它们执行操作。

最佳答案

它们非常相似,但是具有不同的功能:

第二名:


Promise.propsthen仅在没有错误发生时运行。
Promise.props方法使您可以在所有承诺解决方案之后轻松地(更清楚地)运行代码
计算上,您的复杂度为O(2 * N)


第一:


即使出现错误,您也可以获得结果。
您可以实施错误控制(或类似的重试逻辑)
您必须自己同步承诺
计算上,您具有O(N)复杂度

10-05 20:38
查看更多