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?
The function can return a value or a promise object, or can throw an error. If onRejected is provided and doesn't throw an error (or return a promise that fails) then this is the async equivalent of catching an error. If TRUE , ignore the return value of the callback, and use the original value instead.
In a promise nesting when you return a promise inside a then method, and if the returned promise is already resolved/rejected, it will immediately call the subsequent then/catch method, if not it will wait. If promised is not return, it will execute parallelly.
Promise resolve() method:If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
Promise.prototype.then() The then() method returns a Promise . It takes up to two arguments: callback functions for the success and failure cases of the Promise .
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With