Search code examples
node.jsexpresscronreturncron-task

Returning A Value In Node.js Express Using Cron


I've got Cron installed properly and everything, but I'm having trouble accessing a value returned from that function in the rest of my node app.

Basic Function:

module.exports.myFunction = function() {
    var job = new CronJob('00 0-59 * * * *', function() {
        var a = 5;
        var b = 2;

        return a + b;

        }, function () {
        },
        true
    );
}

I would think that returning the value here and then accessing it using a promise in one of my routes files would work, but it consistently returns TypeError: Cannot read property 'then' of undefined, which means undefined is being passed from the function.

Here's the code from my route file:

Tester.myFunction()
        .then(function(data) {
            console.log("Done!");
            console.log(data);

            req.flash('success', "You have successfully started the software!");

            res.render('dashboard');

        })
        .catch(function(err) {
            console.log(err);
        })

Since this isn't working, how can I properly return a value from a function when using Cron? Thanks for the help!


Solution

  • You need to return a Promise from myFunction which resolves with the data you're currently returning, like so:

    module.exports.myFunction = function() {
        return new Promise((resolve, reject) => {
            var job = new CronJob('00 0-59 * * * *', function() {
                    var a = 5;
                    var b = 2;
    
                    resolve(a + b);
    
                }, function() {},
                true
            );
        })
    }
    

    However, since a cron can run multiple times, but promise only resolves once, you can also use EventEmitter.

    Change your myFunction as follows:

    module.exports.myFunction = function() {
        const myFnEventEmitter = new(require('events').EventEmitter)();
        var job = new CronJob('00 0-59 * * * *', function() {
                var a = 5;
                var b = 2;
    
                myFnEventEmitter.emit('started', a + b)
    
            }, function() {},
            true
        );
        return myFnEventEmitter;
    }
    

    And where you're using it, do:

    const myFnEventEmitter = Tester.myFunction();
    myFnEventEmitter.on('started', data => {
        console.log("Done!");
        console.log(data);
        req.flash('success', "You have successfully started the software!");
        res.render('dashboard');
    })