otnieldocs
otnieldocs

Reputation: 325

CasperJS' sendAJAX asynchronous flag set to true failed

I set up a CasperJS script to call my web service (running on localhost:9000).

The webservice containing parameter which is needed to be filled. Let's say an amount parameter, and my webservice saves amount data from its parameter. So I wrote my CasperJS script like this:

casper.then(function(){
    val = this.evaluate(function(){
        //do step #1 ajax request

        var country_amount  = 9;
        var params          = "amount="+country_amount;
        var data            = "amount="+country_amount;
        var wsurl           = "http://localhost:9000/TempCountryAmountREST/setCountryAmount?amount="+country_amount;
        //window.__utils__.echo("Country Amount :"+country_amount);
        return JSON.parse(__utils__.sendAJAX(wsurl, "POST" , null, false, { contentType: "application/json" }));
    });
});

As you can see, in the fourth parameter of __utils__.sendAJAX, I set it up with false, which means asynchronous = false. Well, everything goes well with async = false. That val variable successfully returning json data.

But when I changed false to true, it's coming up with a weird thing. Sometimes it succeeds to save the data (with my webservice), but val doesn't return proper value (it's null, but it should be returning json data). But saving data is still successful when I see on my phpmyadmin. But sometimes too (almost always happened), it fails to save the amount data, and still, returning null (not json data)

So what happened with this, is there a problem with use async request in CasperJS sendAJAX?

Upvotes: 1

Views: 585

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

That is the expected behavior when an execution is asynchronous. Take for example the following code which is asynchronous by using the setTimeout function:

function sendAsync(){
    var returnVal;
    setTimeout(function(){
        returnVal = sendSync();
    }, 100);
    return returnVal;
}

Since setTimeout is asynchronous sendSync is called or even finished after sendAsync finishes. You simply cannot return something based on an asynchronous call. See this question for more information.

__utils__.sendAJAX() doesn't provide a callback which could be used to get the returned data asynchronously. Since you want the data to be returned, you have to set the asynchronous argument to false.

__utils__.sendAJAX() with the asynchronous argument set to true can only be used for so called fire-and-forget requests where you are not interested in the data returned. Usually you're interested in the returned data.

The reason it sometimes fails to properly send and save the data is probably because this is an asynchronous process and your CasperJS script exits before the request is completed, thus terminating your request. By specifying async as true, you essentially make a tiny break off from the control flow.

Upvotes: 2

Related Questions