Node.js – How to return values from nested promise

bluebirdnode.jspromiseredis

I have a set of IDs of movies in Redis: [1,2,3,4] and a set of hashes with the actual data. Now, I want to fetch all the movie data for the IDs in once.

I am trying to use bluebird promisses, but I got stuck. So far, I have:

  function allMovies() {
    var movies, movieIds;
    return client.smembersAsync('movies.ids').then(function(ids) {
      movieIds = ids;
      movies =  _.map(movieIds, function(id) {
         var movie;
         return client.hmgetAsync("movies:" + id, 'title', 'description', 'director', 'year').done(function(data) {
           movie = data;
           return {
                 title: data[0], 
                 description: data[1], 
                 director: data[2],
                 year: data[3]
               };
          });
          return movie;
        });
    })

The problem is from what I try, that I always get back a new promise, while I am just interested in a JSON after all operations have finished.

Anyone here can shed some light into this?

Best Answer

In bluebird, there is a more sugary way of doing this:

function allMovies() {
    return client.smembersAsync("movies.ids").map(function(id){
        return client.hmgetAsync( "movies:" + id, 'title', 'description', 'director', 'year');
    }).map(function(data){
        return {
            title: data[0],
            description: data[1],
            director: data[2],
            year: data[3]
        };
    });
}