【问题标题】:Porting RSVP.js map idiom over to bluebird将 RSVP.js 映射成语移植到 bluebird
【发布时间】:2014-10-11 14:14:12
【问题描述】:

RSVP.js中有一个很优雅的成语:

var promises = [2, 3, 5, 7, 11, 13].map(function(id){
  return getJSON("/post/" + id + ".json");
});

RSVP.all(promises).then(function(posts) {
  // posts contains an array of results for the given promises
}).catch(function(reason){
  // if any of the promises fails.
});

但是,我使用的库已经依赖并公开了一些 bluebird's api。所以我宁愿避免混入 RSVP.js,即使它有时看起来更优雅。

bluebird 中的 RSVP.js 代码 sn-p 的等价物是什么?

【问题讨论】:

  • 还是一样的Promise.all(promises).then(...)

标签: javascript promise bluebird rsvp.js


【解决方案1】:

除了使用 Bluebird 的 Promise 命名空间而不是 RSVP,一切都可以保持不变 - 使用 Promise.all。此外,混合符合 Promises A+ specification 的承诺应该可以很好地工作,因此您甚至可能必须更改任何内容。

虽然我个人不太喜欢它,但 Bluebird 也有自己的成语来完成这项任务 - Promise.map

Promise.map([2, 3, 5, 7, 11, 13], function(id){
  return getJSON("/post/" + id + ".json");
}).then(function(posts) {
  // posts contains an array of results for the given promises
}).catch(function(reason){
  // if any of the promises fails.
});

【讨论】:

  • 谢谢大家,我的类似于上面的真实代码现在可以工作了,确实使用了Promise.all(和一个常规的非 Promises 映射)。我之前刚刚迷失了bluebird map 示例的详细信息(除了.all,它还承诺了一个现有的库和东西。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 2011-03-06
相关资源
最近更新 更多