示例 1:
function abc(){
// code1 takes 5 secs to execute;
// code2 takes 1 sec to execute;
});
casper.then(function(){
abc();
casper.then(function(){
console.log("All statements inside abc functions have been executed");
});
});
我观察到,casperjs 在启动第一个语句后立即启动下一个语句,除非我们使用 casper.then()
。因此,在上面的代码中,code2 无需等待 code1 完成执行即可启动。
我的问题是,一旦 code2 启动,控件是否会返回到调用函数,或者是否会等待函数 abc() 完成执行所有语句。请注意,在调用 abc() 之后的调用函数中有一个 casper.then()
。
如果它不等待 code1 完成,我可以这样做: 示例2:
function abc(){
// code1 takes 5 secs to execute;
// code2 takes 1 sec to execute;
casper.then(function(){
return;
});
});
casper.then(function(){
abc();
casper.then(function(){
console.log("All statements inside abc functions have been executed");
});
});
我希望 console.log() 仅在 abc() 内的所有语句完全执行后才执行。
最佳答案
这实际上取决于 code1
和 code2
是什么。如果它是完全同步的代码,我对此表示怀疑,因为你问了这个问题,你可以在之后使用 then
:
function abc(){
// code1 takes 5 secs to execute;
// code2 takes 1 sec to execute;
});
casper.then(function(){
abc();
casper.then(function(){
console.log("All statements inside abc functions have been executed");
});
});
如果它不是同步的,您需要在完整(或可能被命名)回调中将一些全局变量设置为完成值。然后你waitFor
它的执行:
var globalObj = {};
function abc(){
// code1 takes 5 secs to execute and sets globalObj.code1 = true
// code2 takes 1 sec to execute and sets globalObj.code2 = true
});
casper.then(function(){
abc();
// you can wait for the two async calls separately
casper.waitFor(function check(){
return (code1 in globalObj) && globalObj.code1;
}, null, null, 10000);
casper.waitFor(function check(){
return (code2 in globalObj) && globalObj.code2;
}, null, null, 10000);
// or it can even be combined
casper.waitFor(function check(){
return (code1 in globalObj) && globalObj.code1 && (code2 in globalObj) && globalObj.code2;
}, function then(){
console.log("All statements inside abc functions have been executed");
// you can nest more then or other step functions here,
// if you only want execution for a successful waitFor
}, null, 10000);
// this then is only executed when the waitFor stopped (either because of successful check or because of timeout)
casper.then(function(){
console.log("All statements inside abc functions have been executed");
});
});
顺便说一句,空的 then
block 什么也不做。它对等待或任何事情都没有帮助。您可以完全删除它:
casper.then(function(){
return;
});
关于javascript - 我是否需要将 'return' 语句放在 'casper.then' block 中,以便父函数等待子函数完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580979/