merours
merours

Reputation: 4106

Logs inverted in Javascript

I'm writing some tests with casperjs and I came across something really strange to me :

here is the code :

casper.test.begin('Test', nbTests, function(test) {
    console.log(A_SERVER + A_IMPORT + A_IMPORT_TAB1);
    casper.start(A_SERVER + A_IMPORT + A_IMPORT_TAB1);    
    casper.waitForUrl(A_SERVER + A_IMPORT + A_IMPORT_TAB1, function (){
        console.log("ok");
    }, function(){
        console.log("nok");
    });
    console.log(casper.getCurrentUrl());
    casper.run(function(){
        test.done();
        this.exit();
    });
});

The test runs fine, but logs are displayed this way :

http://127.0.0.1:8000/import/upload/
http://127.0.0.1:8000/import/upload/
ok

Could you tell me why are the two last logs inverted ? I guess it is related to how functions are handled with javascript, but I'd like a more explicit explaination.

Upvotes: 0

Views: 63

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328536

.waitForUrl() creates a background job and returns. When the response from the remote server arrives, it will call the callback function. That is why you see the synchronous

console.log(casper.getCurrentUrl());

first.

are all anonymous functions asynchronous in javascript ?

No. Read the documentation of the frameworks that you use to learn which callbacks are called when.

Generally, many anonymous functions are asynchronous since they are used as event handlers (will only be called once the event happens) or processing AJAX responses (asynchronous by nature).

Upvotes: 2

Related Questions