【问题标题】:Synchronizing with 3rd-party asynchronous API in CasperJS在 CasperJS 中与第三方异步 API 同步
【发布时间】:2023-03-27 02:57:01
【问题描述】:

我觉得有些异步代码应该在 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() 的示例也很受欢迎,但在这种情况下我会收到一种“常见做法”的建议。

【问题讨论】:

    标签: javascript promise casperjs


    【解决方案1】:

    您必须等到子进程退出。这通常使用(全局)变量来完成。它在子进程“退出”的情况下设置,随后的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 的脚本并不是真正基于 Promise 的,这就是为什么必须使用 waitFor() 的原因。请参阅我的回答 here 了解更多信息。

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

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

    【讨论】:

      猜你喜欢
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2015-02-23
      • 2012-11-03
      相关资源
      最近更新 更多