这是我获取存储在 redis 中的用户 php session 的原始代码:
var session_obj;
var key = socket.request.headers.cookie.session
session.get('PHPREDIS_SESSION:'+key,function(err,data){
if( err )
{
return console.error(err);
}
if ( !data === false)
{
session_obj = PHPUnserialize.unserializeSession(data);
}
/* ... other functions ... */
})
我想用Promise重写代码,但是我无法得到返回的data
:
Promise.resolve(session.get('PHPREDIS_SESSION:'+key)).then(function(data){
return data;
}).then(function(session){
console.log(session); // this returns true, but not the session data
session_obj = PHPUnserialize.unserializeSession(session);
}).catch(function(err){
console.log(err);
})
session
只返回 bool 值 true
而不是 session 数据。原始的 redis get
函数有两个参数。我假设 promise 只是返回了第一个参数,原始参数是 err
。所以我尝试了
Promise.resolve(session.get('PHPREDIS_SESSION:'+key)).then(function(err,data){
console.log(data) // return undefined
})
但它也不起作用。
有谁知道 redis 是否可以与 Promise 一起使用?
最佳答案
您尝试使用 Promise.resolve
是错误的,它需要一个 Promise 而 session.get
默认情况下不会返回一个 Promise。你首先需要promisify它。 (或 promisifyAll)
session.getAsync = Promise.promisify(session.get);
// OR
Promise.promisifyAll(session); //=> `session.getAsync` automatically created
// OR
Promise.promisifyAll(redis); //=> Recursively promisify all functions on entire redis
然后像使用 promise 一样使用返回 promise 的新函数,您甚至不需要用 Promise.resolve 包装它,只需这样:
session.get('PHPREDIS_SESSION:' + key).
then(function(data) {
// do something with data
}).
catch(function(err) {
// handle error with err
});
关于javascript - Bluebird Promise 可以在 node.js 中与 redis 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30565855/