简体   繁体   English

Bluebird Promise可以在node.js中使用redis吗?

[英]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: 这是我的原始代码,用于获取存储在redis中的用户php会话:

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重写代码,但我无法获得返回的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);
})

The session returned just boolean true instead of the session data. session只返回布尔true而不是会话数据。 The original redis get function has two arguments. 原始的redis get函数有两个参数。 I assumed the promise just returned the first argument which was err in the original. 我假设承诺刚刚返回了第一个在原文中err参数。 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? 有谁知道redis是否可以与Promise合作?

You were trying to use Promise.resolve wrong, it expects a Promise and session.get by default doesn't return a Promise. 你试图使用Promise.resolve错误,它期望Promise和session.get默认不返回Promise。 You first need to promisify it. 你首先需要宣传它。 (or promisifyAll ) (或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: 然后使用new函数返回promise,就像你使用promise一样,你甚至不需要用Promise.resolve包装它,就这样:

session.get('PHPREDIS_SESSION:' + key).
then(function(data) {
    // do something with data
}).
catch(function(err) {
    // handle error with err
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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