NodeJS回调

时间:2014-01-31 21:58:01

标签: javascript node.js callback

我花了几个小时玩我的回调,但它拒绝工作! '尝试'输出到控制台很好,但它总是拒绝输出'回调'....我错过了什么?

我以前有var output = job.runJob(....工作正常,但是我需要添加一些异步爵士来运行作业!

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

1 个答案:

答案 0 :(得分:1)

您正在向runjob传递四个参数,但runjob只接受3个参数。像这样更改runjob的定义:

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