Search code examples
javascriptnode.jsscopes

node.js: Async.whilst() callback not functioning as expected


So first of all I would just like to say that I would rather use a while() loop or do-while() loop but I have an async "child-process" function that needs to callback stdout. Anyways when running the script, my function is not printing out the console.log() in the command prompt, also it seems that exec is creating multiple processes, even when I add a .kill() function at then end!

My problem I believe is based on scoping but I cannot pinpoint where I am going wrong. So two questions, why is it not possible to use a while loop and what exactly is wrong with my function?

var stdout; 

function checkStatus() {

    async.whilst(
        function(){return stdout != "Connected";},
        function(callback){
            var state;
            state = exec("C:/ADMIN/Viscosity/ViscosityCC.exe "+'getstate '+ 1, function (error, stdout, stderr) {
                stdout = (stdout.toString()).replace("\r\n\r\n", "");
                console.log(stdout);
            });
            state.kill();
            callback();

        },
        function(err){
            console.log("Error");

        }
    );

}

checkStatus();

Solution

  • The problem is you have two variables with the same name:

    var stdout;
    
    // ...
    
    state = exec(
        "C:/ADMIN/Viscosity/ViscosityCC.exe "+'getstate '+ 1,
        function (error, stdout, stderr) {
            stdout = (stdout.toString()).replace("\r\n\r\n", "");
    // which  ^  is the ^  real stdout?
            console.log(stdout);
        }
    );
    

    The solution is to use two different variable names:

    state = exec(
        "C:/ADMIN/Viscosity/ViscosityCC.exe "+'getstate '+ 1,
        function (err, o, e) {
            stdout = (o.toString()).replace("\r\n\r\n", "");
            console.log(stdout);
        }
    );