Search code examples
javascriptpromisebluebirdrsvp.js

Porting RSVP.js map idiom over to bluebird


In RSVP.js, there is a very elegant idiom:

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.
});

However I am using a library that already relies on, and exposes some of bluebird's api. So I'd rather avoid mixing in RSVP.js even if it may seem at times more elegant.

What would be the equivalent in bluebird, of the RSVP.js code snippet above?


Solution

  • Except for using Bluebird's Promise namespace instead of RSVP, everything can stay the same - using Promise.all. Also, mixing promises that conform to the Promises A+ specification should work well, so you might not even have to change anything.

    While I personally don't like it much, Bluebird also has its own idiom for this task - 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.
    });