Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Async: Callback already called?

I'm using Async module in Node.JS to keep track of my asynchronous calls. However, I'm getting an error - "Callback already called." Can someone help me out here?

async.each(data['results'], function(result, done) { 
    if (result['twitter_id'] !== null) { //Isolate twitter handle
        var param = { "user.screen_name": result['twitter_id']}
        db.test4.find( param, function(err, users) {
            if( err ) {
                return done(err);
            } else if (!users) {
                res.send("No user found");
            } else {
                users.forEach( function(Result) { 
                    twitter_ids.push(Result);
                    //console.log(Result);
                    done();
                });
            }
        });
    }
}, function(err) {  
    if (err) {
        throw err
    }
    res.send(twitter_ids);
});
like image 592
techalicious Avatar asked Jun 27 '14 22:06

techalicious


1 Answers

You're calling res.send("No user found"); each time you fail to load. However you can fail to load multiple times.

The solution is to put all your response code in the final callback, not in the each callback.

async.each(data['results'], function(result, done) { 
    if (result['twitter_id'] !== null) { //Isolate twitter handle
        var param = { "user.screen_name": result['twitter_id']}
        db.test4.find( param, function(err, users) {
            if( err ) {
                done(err);
            } else if (!users) {
                done(new Error("No user found"));
            } else {
                users.forEach( function(Result) { 
                    twitter_ids.push(Result);
                    //console.log(Result);
                });
                done();
            }
        });
    } else {
      done();
    }
}, function(err) {  
    if (err) {
        return next(err);
    }
    res.send(twitter_ids);
});
like image 65
generalhenry Avatar answered Nov 05 '22 15:11

generalhenry