2015-06-18 21 views
3

在這裏,我感覺有些異步代碼應該在casper.then()回調中運行。在CasperJS中與第三方異步API同步

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()的示例也值得讚賞,但在這種情況下,我會收到一些「常見做法」建議。

回答

0

您必須等到子進程退出。這通常使用(全局)變量完成。它是在子進程「退出」的情況下設置的,隨後的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()。有關更多信息,請參閱我的回答here

相反的casper.waitFor()可以使用無限WAITFOR:

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