简体   繁体   中英

Can Bluebird Promise work with redis in node.js?

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?

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM