Reputation: 4748
Here's my original code to fetch a user php session which is stored in redis:
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 ... */
})
I would like to rewrite the code with Promise, but I can't get the data
returned:
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);
})
The session
returned just boolean true
instead of the session data. The original redis get
function has two arguments. I assumed the promise just returned the first argument which was err
in the original. So I tried
Promise.resolve(session.get('PHPREDIS_SESSION:'+key)).then(function(err,data){
console.log(data) // return undefined
})
but it wasn't working either.
Does anyone know if redis could work with Promise?
Upvotes: 1
Views: 2771
Reputation: 34627
You were trying to use Promise.resolve
wrong, it expects a Promise and session.get
by default doesn't return a Promise. You first need to promisify it. (or 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
Then use the new function which returns the promise like you would use a promise, you don't even need to wrap it with Promise.resolve, just this:
session.get('PHPREDIS_SESSION:' + key).
then(function(data) {
// do something with data
}).
catch(function(err) {
// handle error with err
});
Upvotes: 3