Redis命令的执行异步 [英] Async execution of redis commands

查看:260
本文介绍了Redis命令的执行异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行的Redis的几个异步方法有以下code

I'm trying to execute several async methods of redis with the following code

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;
    });

所有方法成功执行

但我得到的错误 [类型错误:对象真​​的没有方法'申请']

执行方法,并返回true,它可能是间preting,作为真实的,但我不明白为什么它使用的方法适用于它?

the method is executed and returns true, and its probably interpreting that as true, but i don't see why it has to use the method apply on it?

我可以通过添加功能(犯错,结果),以作为client.hincrby最后一个元素得到增量的结果..但我如何得到所有的结果到底函数结果变量?

I can get the result of the increment by adding a function(err, result) to client.hincrby as last element.. but how do i get all the results in the result variable in the end function?

推荐答案

我想你使用asyncjs模块是一个记录的:
https://github.com/fjakobs/async.js

I suppose the asyncjs module you use is the one documented at: https://github.com/fjakobs/async.js

在您的code:


  • 列表()是发电机。它允许阵列由asyncjs迭代。该阵列是值的阵列。

  • ()的调用是一个一个映射器调用每个项目。因此,该项目已经可以被调用(即他们必须回调)。

  • 结束()是一个终端终点,当迭代结束调用。作为一个参数,你只能得到序列(而不是整个序列)的最后一个值。

  • list() is a generator. It allows the array to be iterated by asyncjs. The array is an array of values.
  • call() is a mapper which calls each item. The items has therefore to be callable (i.e. they have to be callbacks).
  • end() is a termination end point, called when the iteration is over. As a parameter, you only get the last value of the sequence (not the whole sequence).

您拿到 [类型错误:对象真​​实没有方法'申请'] 的错误,因为你已经建立的列表不是回调的列表。它是值的列表

You got the "[TypeError: Object true has no method 'apply']" error because the list you have built is not a list of callbacks. It is a list of values.

下面是一些code应该做你想要的:

Here is some code which should do what you want:

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()

请注意这里我们使用的地图()而不是调用()和的toArray()而不是结束()。

Please note here we use map() instead of call(), and toArray() instead of end().

这篇关于Redis命令的执行异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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