Synchronization with 3rd party asynchronous API in CasperJS

This is where I feel stuck with some asynchronous code that needs to run inside a callback casper.then()

.

casper.then(function() {
    var spawn = require("child_process").spawn;
    var child = spawn("somecommand", ["somearg"]);
    child.stdout.on("data", function (data) {
      console.log("spawnSTDOUT:", JSON.stringify(data))
    });
});

casper.then(function () {
  // Something that should be synchonized
});

      

Is there a way to make sure the second one then()

is only executed after the data callback fires?

I would like to replace the first then()

one with one that will not pass the control to the second then()

after execution by default, and would rather do this by calling something (let it "solve" as the promise of the template suggests) in the data callback.

Examples using are also welcome casper.waitFor()

, but in this case I would get a kind of "common practice" suggestion.

+3


source to share


1 answer


You need to wait for the child process to finish. This is usually done with a (global) variable. It is set if the child process "exits", and the next one casper.waitFor()

will wait for this variable to be true. You may need to adjust the timeout.

casper.then(function() {
    var spawn = require("child_process").spawn;
    var child = spawn("somecommand", ["somearg"]);
    child.stdout.on("data", function (data) {
      console.log("spawnSTDOUT:", JSON.stringify(data))
    });

    var childHasExited = false;
    child.on("exit", function (code) {
      childHasExited = true;
    })

    this.waitFor(function check(){
      return childHasExited;
    }, null, null, 12345); // TODO: adjust the timeout
});

casper.then(function () {
  // Something that should be synchonized
});

      

CasperJS script is not really promises based, so it waitFor()

should be used. See my answer here for details .



Instead, casper.waitFor()

you can use the infinite waitFor:

casper.infWaitFor = function(check, then) {
    this.waitFor(check, then, function onTimeout(){
        this.infWaitFor(check, then);
    });
    return this;
}

      

0


source







All Articles