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?

有帮助吗?

解决方案

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

其他提示

If Bluebird is consistent with Q on this issue, it’s just a matter of taking your array of promises and turning them into a promise for the array of results. Note the addition of Q.all to your example, the return inside the handler, and the use of then instead of done to chain the movie promise.

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')
           .then(function(data) {
               return {
                   title: data[0], 
                   description: data[1], 
                   director: data[2],
                   year: data[3]
                };
            });
        });
        return Q.all(movies);
    })
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top