javascript - 将 RSVP.js map idiom 移植到 bluebird

标签 javascript promise bluebird rsvp.js

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 代码片段?

最佳答案

除了使用 Bluebird 的 Promise 命名空间而不是 RSVP 之外,一切都可以保持不变 - 使用 Promise.all .此外,混合符合 Promises A+ specification 的 promise 应该运行良好,因此您甚至可能无需更改任何内容。

虽然我个人不太喜欢它,但 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.
});

关于javascript - 将 RSVP.js map idiom 移植到 bluebird,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367146/

相关文章:

javascript - 在 Bluebird Promise 中动态定义函数

javascript - 由于异步生成器中的非并行等待 promise 而减速

javascript - float和int之和返回不寻常的小数位js

javascript - 如何让 TeamCity 更新指定文件中的构建版本号?

javascript - 返回用于点击处理程序的 promise

javascript - 如果没有 Q.resolve,promise 如何得到解决

javascript - 输入后立即获取变量

javascript - beforeunload 事件和 Content-Disposition=attachment

javascript - 异步 ES2017 构造函数

node.js - 在使用 Bluebird promise mongodb 后,使用 mongodb 的查找游标的 next/each 函数作为 promise 的方法