Scott Robinson
Scott Robinson

Reputation: 605

NodeJS Callbacks

I've spent a few hours playing with my callback but it refuses to work! 'trying' outputs to the console fine, but it always refuses to output 'callback here'.... Am I missing something?

I previously has var output = job.runJob(.... which worked fine, but I needed to add in some async jazz for job's to run!

jobscheduler.js

job = require("./job"),

console.log('trying');
job.runJob(item.definition,item.vars,item._id, function(callback) {
    console.log('['+item._id+'] Job output = '+callback);
    console.log('callback here');

    // Update job nextrun time
    var nextrun = new Date();
    nextrun.setSeconds(nextrun.getSeconds() + 10);

    collection.update({'_id':item._id}, {$set: {nextrun:nextrun}}, {safe:true}, function(err, result) {
        if (err) {
                console.log('Error updating item: ' + err);
            } else {
                console.log('['+item._id+'] Job was updated. Next run is '+nextrun);
            }
        });
});

job.js

var jobdef = require("./jobdef");

module.exports = {
    runJob : function(job,vars,jobid){
        if (typeof jobdef[job] == 'function') { 
            var output = jobdef[job](vars,jobid);
            return output;
        } else {
            console.log('['+jobid+'] Job def \'%s\' does not exist. Check jobdef.js for definitions.',job);
        }
    }
};

jofdef.js

module.exports = {
    ping : function(vars,jobid){
        return('Were in ping');
    },

    urlopen : function(vars,jobid){
        return('Were in urlopen');
    },

    findstr : function(vars,jobid){
        return('Were in findstr');
    }
};

Upvotes: 0

Views: 137

Answers (1)

Paul
Paul

Reputation: 141829

You are passing four arguments to runjob, but runjob only takes 3 arguments. Change the definition of runjob like so:

module.exports = {
    runJob : function(job, vars, jobid, callback){
        if (typeof jobdef[job] == 'function') { 
            var output = jobdef[job](vars,jobid);
            if (typeof callback === 'function')
                callback(output);
        } else {
            console.log('['+jobid+'] Job def \'%s\' does not exist. Check jobdef.js for definitions.',job);
        }
    }
};

Upvotes: 1

Related Questions