简体   繁体   中英

How to export a variable from a scheduled function

I have a function that gets input constantly but then only processes it every minute with a cron job.

The most recent output should be stored in a variable and retrieved from the outside at random times.

Here in a very simplified form:

let input = 'something';

let data = '';
data += input;

require('node-schedule').scheduleJob('* * * * * *', somethingMore);

function somethingMore() {
let output = data += 'More';
// return output;
}

console.log(output);

Initializing the variable outside the function like above doesn't seem to work in this case.

Calling the function directly or assigning it to a variable doesn't help, as it would run it before it's due.

I also tried with buffers, but they don't seem to work either, unless I missed something.

The only thing that does work is writing a file to disk with fs and then reading from there, but I guess it's not the best of solutions.

It seems like you just let your chron function run as scheduled and you save the latest result in a module-scoped variable. Then, create another exported function that anyone else can call to get the latest result.

You will have to implement that part yourself.

// module-scoped variable to save recent data
// you may want to call your function to initialize it when
// the module loads, otherwise it may be undefined for a little bit
// of time
let lastData;

require('node-schedule').scheduleJob('* * * * * *', () => {
     // do something that gets someData
     lastData = someData;
});

// let outside caller get the most recent data
module.exports.getLastData = function() {
    return lastData;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM