node.js如何从中间件

时间:2018-06-18 21:34:12

标签: node.js redis

我正在做中间件模块,它将从redis中提取数据并放入req.my_session。[here]

这是在app.use();

中调用的函数
  function parse_cookies(req){
      if(req.headers.cookie != null){
        var result = req.headers.cookie.match(new RegExp('m:[^=]*=[^; ]*', 'ig'));
        if(result != null){
          for(var i = 0; i < result.length; i++){
            var result1 = result[i].split('=');
            req.my_session[result1[0].substr(2)] = result1[1];
            // get from redis value
            client.get('sess:'+result1[1], function(err, reply) {
              // reply is null when the key is missing
              console.log(reply);
              let li = i;
              req.my_session[result1[0].substr(2)] = reply;
              console.log('li = ' + li);
              console.log('result1.lenght= ' + result.length);
              if(i == result.length){
                console.log('call the next');
              }
            });
          }
        }
      }
    } // parse_cookies

在控制台i输出总是3,如何使用redis.get从数据库获取所有数据,并在最后一次数据调用next()函数从我的函数中输出?

problem it's get data from database in my middleware, I can't because redis has callback function

    client.get("missingkey", function(err, reply) {
    // reply is null when the key is missing
    console.log(reply);
});

1 个答案:

答案 0 :(得分:0)

我认为问题是因为你可以尝试下面的异步循环

  function parse_cookies(req){
      if(req.headers.cookie != null){
        var result = req.headers.cookie.match(new RegExp('m:[^=]*=[^; ]*', 'ig'));
        if(result != null){
          var promises = [];
          for(var i = 0; i < result.length; i++){
            var result1 = result[i].split('=');
            promises.push(getFromRd(req, result1));

          }

          return Promise.all(promises)
                 .then(() => {
                      return next()
                 })
                 .catch((e) => {
                      return next({error: e})
                 })
        }
      }
    } // parse_cookies


  function getFromRd(req, result1) {
         req.my_session[result1[0].substr(2)] = result1[1];
         // get from redis value
         return client.get('sess:'+result1[1], function(err, reply) {
                if (err) {
                    throw Error(' failed to find ' + 'sess:' + result1[1])
                }
                // reply is null when the key is missing
                console.log(reply);
                let li = i;
                req.my_session[result1[0].substr(2)] = reply;
                console.log('li = ' + li);
                console.log('result1.lenght= ' + result.length);
                return {success:true}
            });
  }