Captain Obvious
Captain Obvious

Reputation: 785

Async execution of redis commands

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

All the methods execute successfully

but i get the error [TypeError: Object true has no method 'apply']

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?

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?

Upvotes: 1

Views: 3099

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73306

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

In your code:

  • 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.

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

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

Upvotes: 1

Related Questions