JavaScript / Ajax async problem

Soldato
Joined
17 Oct 2002
Posts
4,308
Location
Bristol
Basically I'm testing some javascript with two pretty complicated systems and I don't really know javascript that well, but it boils down to the problem below.

I am calling the javascript function below from another system, all this system can do is call the script and return the return type as a string.

The following code basically makes async calls to a url and returns some json, problem I have is the function finishes and returns before I can assert the content of the variables, how do wait till my variables are not null?

Code:
function test2(){
    var wrapper = new music.ApiWrapper(null);
    var returnContentSuc = null;
    var returnContentErr = null;
    
    wrapper.doSearch({
        q: 'snoop'
    }, function(responseObj){
        alert('search successfull callback');
	returnContentSuc = responseObj;
    },function(errorResult){
    	alert('search error calback');
	returnContentErr = errorResult;
    });

    **How do I wait here until my returnContent variables are not null?**     

    //assert the returned variables here are correct and return pass fail  
    return pass/fail;
};

Thanks for any help
 
You need to use Synchronous AJAX - http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX.

AJAX doesn't wait for a response before the rest of the Javascript continues executing, which is why you're not getting a result. The reason being is that blocking whilst waiting for a response from a slow server would cause your page to hang which for the most part isn't what you want.
 
Thanks, looks like I'm a bit screwed then as I can't alter the code in the 'wrapper' object, its existing production code. I'll just have to look for an alternative, was just hoping I could test this code in a framework I'm using for other bits which isnt designed for JS but its proving too difficult.
 
Back
Top Bottom