与 CasperJS 中的第三方异步 API 同步

Synchronizing with 3rd-party asynchronous API in CasperJS

本文关键字:异步 API 同步 第三方 CasperJS      更新时间:2023-09-26

在这里,我感到被一些应该在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
});

有没有办法确保第二个then()仅在数据回调触发后执行?

我很想用默认情况下不会在执行后将控制权传递给第二个then()的东西替换第一个then(),而是通过在数据回调中调用某些东西(我们称之为"解析",因为承诺模式所暗示)来做到这一点。

使用casper.waitFor()的例子也值得赞赏,但在这种情况下,我会收到一种"常见做法"建议。

您必须等到子进程退出。这通常使用(全局)变量完成。它是在子进程"退出"的情况下设置的,后续casper.waitFor()将等到该变量为真。您可能需要调整超时。

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的脚本并不是真正基于承诺的,这就是为什么必须使用waitFor()。请参阅我的答案 这里 了解更多信息。

您可以使用无限等待来代替casper.waitFor()

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