javascript - 我是否需要将'return'语句放入'casper.then'块中,以使父函数等待子函数完成执行?

范例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");
    });
});


我观察到,除非我们使用 casper.then(),否则casperjs会在启动第一条语句后立即启动下一条语句。因此,在上面的代码中,无需等待代码1完成执行即可启动代码2。

我的问题是,控件是否在code2启动后立即返回到调用函数,还是等待函数abc()完成所有语句的执行。请注意,在调用abc()之后,调用函数中有一个 casper.then()

如果它不等待代码1完成,我可以这样做:
范例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");
    });
});


我希望仅在abc()内部的所有语句都已完全执行后才执行console.log()。

最佳答案

这实际上取决于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");
    });
});


如果它不是同步的,则需要在完整(或可能命名)回调中将一些全局变量设置为结束值。然后,您 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;
});