Search code examples
node.jsasynccallback

Async utility for Node.js Call back function not executing


I am trying to use the async utility for the node.js. Below is my code. The console prints "In my func1" and "In my func2". I also expect it to print "call back func" but it won'nt

var myfunc1 = function(callback) {
var a = 1;
console.log ("In my func1");
};
var myfunc2 = function(callback) {
var b = 2;
console.log ("In my func2");
};

models.Picture.prototype.relativeSort = function(viewer_location) {
console.log("Rel Sort");

var sortedPics = [];
var relsortedPics = [];

 // Finds all the pictures
 async.series([myfunc1(), myfunc2()],
 function(err, results){
    if(err) {
        throw err;
    }
 console.log("call back func");
    return a+b;
    });
 };

Solution

  • You need to use the callback argument, for example:

    var myfunc1 = function(callback) {
        var a = 1;
        console.log ("In my func1");
        callback(null, 'test');
    };
    

    The first argument of callback is an error, and the second the result you want to pass to the final handler.

    EDIT

    I've missed the other mistake. This line:

    async.series([myfunc1(), myfunc2()],
    

    should be

    async.series([myfunc1, myfunc2],
    

    You are not supposed to call functions. You are telling async: "Hey, take these functions and do something (asynchronous) with them!".