我需要把'return'casper.then'块,让父函数等待子函数完成执行

Do I need to put the 'return' statement inside a 'casper.then' block for the parent function to wait for the child function to complete execution?

本文关键字:等待 函数 子函数 执行 then return casper      更新时间:2023-09-26

示例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()中的所有语句完全执行后才执行。

这取决于code1code2是什么。如果它是完全同步的代码,我怀疑,因为你问了这个问题,你可以使用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");
    });
});

如果它不是同步的,则需要在complete回调(或其他可能命名的回调)中将一些全局变量设置为finish值。然后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块什么也不做。这对等待没有任何帮助。你可以完全删除这个:
casper.then(function(){
    return;
});

就我在文档中看到的而言,您应该将这些步骤声明为彼此相邻,而不是在彼此之间

所以,你应该使用:

casper.then(function() {
    abc();
});
casper.then(function() {
    console.log('all statements have been executed');
});

查看更多信息:http://docs.casperjs.org/en/latest/modules/casper.html#then