For循环从redis延迟获取项目 [英] For loop get items from redis delay

查看:34
本文介绍了For循环从redis延迟获取项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有node_redis的Node.js,并遍历一个对象并在Redis中查找数据,然后返回结果.

I'm using Node.js w/ node_redis and am looping through an object and looking up data in Redis, then returning results.

我将其设置如下:

        for (var key in items) {
            if (items.hasOwnProperty(key)) {

                    app.client.llen(items[key].id+'_click', function(err, total) {
                        items[key].total = total;

                    });
            }
        }

       callback(items);

问题在于它会在完成对redis的调用之前循环通过.因此,在实际更新总值之前,将调用该回调.由于延迟,它似乎也跳过了一些项目.

The problem is that it loops through, before completing the call to redis. So the callback is called, before it's actually updated the total value. It also seems to skip some items due to the delay.

有没有更好的方法来解决这个问题?

Is there a better way to handle this?

谢谢!

好,所以我已经这样更新了:

Ok, so I've updated it like this:

   getTotal(function () {
       callback(items);
   });

   getTotal = function (callback) {

       var count = 1;

       for (var key in items) {
           if (items.hasOwnProperty(key)) {
               app.client.llen(items[key].id + '_click', function (err, total) {
                   items[key].total = total;

                   if (items.length == count) {
                       callback();
                   }

                   count++;
               });
           };
       }

这似乎可行,它在适当的时间触发了回调,但是似乎只有最后一个键正在进行总更新.

This seems like it would work, it triggers the callback at the appropriate time, however it seems only the last key is getting total updated.

推荐答案

您的第一个示例无法正常工作,因为循环是同步的,而Redis客户端调用是异步的.您的第二个示例由于JavaScript闭包管理而无法更好地工作.您需要在循环本身中提供适当的作用域,以便正确处理闭包,并相应地更新所有字段.

Your first example cannot work because a loop is synchronous while the Redis client calls are asynchronous. Your second example does not work much better because of Javascript closure management. You need a proper scope in the loop itself so the closure is handled correctly, and all the total fields updated accordingly.

在这里使用forEach似乎更容易:

Using forEach seems to be easier here:

getTotal = function (callback) {
  var count = 0;
  Object.keys( items ).forEach( function(key) {
    ++count;
    app.client.llen(items[key].id + '_click', function (err, total) {
      items[key].total = total;
      if ( --count == 0 ) {
        callback( items );
      }
    })
  })
}

getTotal( function(items) {
  console.log( items );
})

这篇关于For循环从redis延迟获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆