How to collect the value to an array in Nodejs loop?

前端 未结 2 369
温柔的废话
温柔的废话 2021-01-16 14:35

I wrote the code below, trying to collect the videos in an array then return. The code is wrong But I can\'t figure out the right way to do this.

var redis          


        
相关标签:
2条回答
  • 2021-01-16 15:27

    Presumably the .hkeys method is asynchronous. That means you have to write code that knows when all async items are done so you can then (and only then) to your final res.send() with the accumulate of results.

    There are many ways to keep track of when all the async operations are complete. My favorite is to promisfy all the involved functions and use Promise.all(). But, since you aren't using promises in this code yet, here's a method using a manual counter. Increment the counter whenever you start an async task. Decrement the counter whenever you finish an async task. When the counter hits zero, all async operations are done:

    var redis = require('redis');
    var client = redis.createClient();
    
    app.get('/topvideos', function(req, res){
      res.type('application/json');
      var topvideos = [];
      var cntRemaining = 0;
    
      client.hkeys("topvideos", function(err,replies) {
        console.log("Results for video:");
        console.log(replies.length + " videos:");
    
        replies.forEach(function (reply, i) {
          ++cntRemaining;
    
          client.hget("topvideos",i, function (err, reply) {
            console.log(i + ": " + reply );
            topvideos.push(reply);
            --cntRemaining;
            if (cntRemaining === 0) {
               res.send(JSON.stringify(topvideos));
            }
          });
        });
    
      }
    });
    
    0 讨论(0)
  • 2021-01-16 15:31

    You can use hgetall

    client.hgetall("topvideos", function(err, videos){
      var keys = Object.keys(videos);
      res.send(JSON.stringify(keys.map(function(key){return videos[key];})));
    });
    

    Documentation

    Also, I recommend to wrap all separate tasks with separate functions, like:

    var async = require('async');
    
    function getKeyValueMap(obj) {
       return function(key, next) {
         return next(null, obj[key]);
       }
    }
    
    function getValues(obj, next) {
        async.map(Object.keys(obj), getKeyValueMap(obj), next);
    }
    
    function getVideoList(next) {
      client.hgetall("topvideos", function(err, videos){
        if (err) return next(null, []);
        getValues(videos, next);
      });
    }
    
    function response(err, data) {
      if (err) return res.send(err.message)
      return res.send(JSON.stringify(data));
    }
    
    getVideoList(response);  
    
    0 讨论(0)
提交回复
热议问题