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

查看:39
本文介绍了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天全站免登陆