Reputation: 501
My child.stderr.on()
and child.stderr.on()
both use a callback which returns a duration value(its just a number representing an execution time in ms).
I'd like to use this in my child.on()
. I thought I could declare a variable outside the functions, assign the duration to it in my functions then use it in my child.on()
. I've included my fnctions below. The child.stdout.on
is the same as child.stdout.on
. Can this be done?
child.stdout.on('data', function(data, callback) {
getEventLog.getId(id, uuid, function(err, id, code, callback){
//if(err) return console.log(err)
console.log("ID: " + id);
getEventLog.getDuration(id, uuid, function(err, duration, callback){
jobRun.duration = duration;
})
});
});
child.on('close', function(code, duration) {
var logMessage =
"Completed jobRunId " + jobRun.id + " (" + jobRun.jobsId + ") " + jobRun.jobType +
" run " + jobRun.runNumber + " in " + jobRun.duration + " with exit code " + code;
jobLogger.info(logMessage + "<br />");
callback(jobRun.id);
});
When I run the above I get this:
Completed jobRunId 818 (601) teragen run 6 in 9813ms with exit code undefined
Upvotes: 0
Views: 49
Reputation: 315
The biggest possible issue with this is that you're running in an asynchronous environment. That means that while you CAN do it this way, there's no guarantee you're going to have any given assignment on your variable at a given time unless, for example, you're assigning it a value once at the very beginning.
The short answer is yes, it will work as you expect.
The long answer is that unless you are guaranteed to have at least one "child.stdout.on('data'" call before you have a "child.on('close'" call, your variable may not be updated. (And in an asynchronous environment, that sort of code isn't usually a good idea, because you don't know WHEN something is going to happen.)
Upvotes: 2