3

Here I'm feeling stucked with some asynchronous code that should run inside a casper.then() callback.

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 any way to make sure that the second then() will be executed only after the data callback fires up?

I'd love to replace the first then() with something that will not pass the control to second then() after execution by default, and would rather do this by calling something (let's call it 'resolve' as the promise pattern suggests) in the data callback.

Examples that are making use of casper.waitFor() are also appreciated, but I'd receive a sort of 'common practice' suggestion in that case.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
vdudouyt
  • 843
  • 7
  • 14

1 Answers1

0

You have to wait until the child process exits. This is usually done with a (global) variable. It is set in the event of an "exit" of the child process and the subsequent casper.waitFor() will wait until that variable is truthy. 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' scripting isn't really based on promises which is why waitFor() must be used. See my answer here for more.

Instead of casper.waitFor() you can use an infinite waitFor:

casper.infWaitFor = function(check, then) {
    this.waitFor(check, then, function onTimeout(){
        this.infWaitFor(check, then);
    });
    return this;
}
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222