我需要一个由数据库查询备份的 redis 查询的异步包装器。如果 redis 查询失败,我想进行 db 查询。如果db查询成功,我想在返回前将返回的数据添加到redis中。我需要函数(希望是对象上的几个这样的方法之一)来返回一个 promise ,因为它将从 node.js 中调用。 我正在使用 bluebird promise 库,并用它来 promise redis。我正在为数据库使用 mongo-gyro,它也是基于 bluebird 的。这两个都是独立工作的。
非常感谢任何帮助 - 甚至是伪代码 - 特别是。错误处理
function get_something(key){
redis.get(key).done(function (res){
if (null !== res){
return res; // how do I return a promise here?
}
})
.done(function (res){
db.find({'_id:key'}).done(function (res){
if (null !== res){
redis.set(key,result) // set db value in redis
.then(function(){
return res; //how do I return a promise here?
})
.catch()...?
return res; // how do I return a promise here?
}
})
.catch...?
};
更新:下面的函数有效,最后显示来自 redis 或 mongo 的数据。但是 - 到目前为止,我一直没有成功将其转换为类的方法,该方法返回一个返回到 node.js 处理程序的 promise 。注意 - 我需要添加“绑定(bind)”以捕获数据源
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' // we got from db
return db.findOne('objects',{'_id':oid})
}
data = JSON.parse(res)
this.from = 'redis' // we got 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){ // at this point, res is not a promise
console.log('result from ' + this.from)
console.log(res)
});
最佳答案
.done
终止 promise 链。一般来说,Bluebird 足够聪明,可以自行计算未处理的拒绝。
它是 .then
你要找的:
redis.get(key).then(function(res){ res is redis .get response
if(res === null) throw new Error("Invalid Result for key");
return db.find({"_id":key); // had SyntaxError here, so guessing you meant this
}).then(function(res){ // res is redis .find response
return redis.set(key,result);
}).catch(function(k){ k.message === "Invalid Result for key",function(err){
// handle no key found
});
关于javascript - 我怎样才能把几个 Bluebird promise 包装在一个 promise 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375651/