【问题标题】:Async execution of redis commandsredis命令的异步执行
【发布时间】:2013-03-22 19:59:09
【问题描述】:

我正在尝试使用以下代码执行redis的几个异步方法

var redis = require("redis");
var client = redis.createClient();
var async = require("asyncjs");

   async.list([
        client.hincrby("traffic:" + siteId, 'x', 1),
        client.hincrby("traffic:" + siteId, 'y', 1),
        client.hincrby("traffic:" + siteId, 'z', 1)
    ]).call().end(function(err, result)
    {
        console.log(err); // returns error [TypeError: Object true has no method 'apply']
        console.log(result); // undefined
        if(err) return false;
        return result;
    });

所有方法执行成功

但我收到错误 [TypeError: Object true has no method 'apply']

该方法被执行并返回true,它可能将其解释为true,但我不明白为什么它必须使用方法apply?

我可以通过将函数(错误,结果)作为最后一个元素添加到 client.hincrby 来获得增量的结果。但是如何在最终函数的结果变量中获得所有结果?

【问题讨论】:

  • 有什么重新定义了控制台对象吗?
  • 我不明白你的意思?
  • 我对@9​​87654323@ 一无所知,但我看到有人重新定义控制台(尤其是console.log)以提供不同功能的示例代码。也许这发生在这里,并且您的(本地)console.log 实现需要一个具有“应用”方法的输入对象?
  • 嗯,不,这不应该是问题..我没有覆盖我所知道的任何东西..我认为它与'end'功能有关,因为一切都成功执行了..谢谢不过!

标签: javascript asynchronous redis


【解决方案1】:

我想您使用的 asyncjs 模块是记录在以下位置的模块: https://github.com/fjakobs/async.js

在您的代码中:

  • list() 是一个生成器。它允许数组被 asyncjs 迭代。该数组是一个值数组。
  • call() 是一个调用每个项目的映射器。因此,这些项目必须是可调用的(即它们必须是回调)。
  • end() 是一个终止点,在迭代结束时调用。作为参数,您只能获取序列的最后一个值(而不是整个序列)。

您收到“[TypeError: Object true has no method 'apply']”错误,因为您构建的列表不是回调列表。它是一个值列表。

这里有一些代码可以做你想做的:

var redis = require("redis");
var client = redis.createClient();
var async = require("asyncjs");

function main() {

  var siteId = 1;

  async
    .list(['x','y','z'])
    .map( function (item,next) {
      client.hincrby('traffic:' + siteId, item, 1, function (err,res) {
        next(err,res)
      })
    })
    .toArray( function(err,res) {
      console.log(err); 
      console.log(res); 
    });
}

main()

请注意,这里我们使用 map() 代替 call(),使用 toArray() 代替 end()。

【讨论】:

  • 是的,这行得通!我已经用一些额外的代码修复了它,但这就是我正在寻找的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 2014-10-08
  • 1970-01-01
  • 2016-01-16
相关资源
最近更新 更多