Seeking assistance in creating an async wrapper for a redis query supported by a db query. If the redis query fails, I want to execute the db query instead. When the db query is successful, I aim to store the returned data in redis before sending it back. The function should ideally return a promise as it will be invoked within node.js. I am currently utilizing the bluebird promises library and using it to promisify redis. For the database, I am using mongo-gyro which is also based on bluebird. Both of these libraries work independently.
Any support would be highly valued - even if it's just pseudocode - particularly with error handling included.
function get_something(key){
redis.getAsync(key).then(function (res){
if (null !== res){
return Promise.resolve(res);
}
})
.then(function (res){
db.find({'_id:key'}).then(function (res){
if (null !== res){
redis.setAsync(key,result)
.then(function(){
return Promise.resolve(res);
})
.catch(...);
return Promise.resolve(res);
}
})
.catch(...);
};
Update: the following function works fine, with the final 'then' displaying data from redis or mongo. However, I have struggled to convert this into a method within a class that returns a promise to pass back to the node.js handler. Note that I had to add 'bind' to capture the source of the data
var oid = '+++++ test oid ++++++'
var odata = {
'story': 'once upon a time'
}
var rkey = 'objects:'+ oid
redis.getAsync(rkey).bind(this).then(function(res){
if(res === null){
this.from = 'db'
return db.findOne('objects',{'_id':oid})
}
data = JSON.parse(res)
this.from = 'redis'
return data
})
.then(function(res){
if(res !== null && this.from == 'db'){
data = JSON.stringify(res)
redis.setAsync(rkey,data)
}
return res
})
.then(function(res){
console.log('result from ' + this.from)
console.log(res)
});