How to pass data from the “then” methods in CasperJS?

﹥>﹥吖頭↗ 提交于 2019-12-05 23:37:33

问题


It's common to have multiple then methods when working with CasperJS. The following is an example:

casper.then(function(){
    var a = "test";
    // ...
})

casper.then(function(){
    // how to use the variable a in the first "then"
})

My question is, what's the common way to pass values from former thens to following thens? For the aforementioned example, how to use a in the second then?


回答1:


There are many way, but the easiest would be to use global variables. If you don't want to clutter your scripts with global variables (which should not be of the same concern as global variables in the browser, because there you could have different libraries), you can use IIFEs to reduce the scope.

casper.start(url);
(function(casper){
    var a;
    casper.then(function(){
        // set a
    }).then(function(){
        // use a
    });
})(casper);
casper.run();

Another version of the global one is to add those variables to the casper object.

Probably the cleanest solution would be to nest those blocks that need the variable. You have to keep in mind that a synchronous function call cannot come after an asynchronous one (those are all wait* and then* step functions). Scheduled steps are executed after the current stap has ended:

casper.start(url).then(function(){
    var a; // set a somehow
    this.then(function(){
        // use a
    });
}).then(function(){
    // don't use a
}).run();


来源:https://stackoverflow.com/questions/26538463/how-to-pass-data-from-the-then-methods-in-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!