views:

76

answers:

3

I am having a really peculiar case. I want to return some data - data that is downloaded via ajax. So far async & sync modes don't get the data in time to the return. Is it possible I could either call return from a child function for the parent function or could a timeOut solve the issue? I can't think of another way of doing this, but the data must be returned.

A: 

Just pass false as a third parameter to to XMLHttpRequest.open. It means "run this query synchronously".

See the reference for yourself.

zneak
I'd love if `$.ajaxSetup({ async:false })` would work for me, it'd solve all my problems but my code seems to ignore it?
Kyle
+1  A: 

You could provide a callback function:

function parentfunction(callback) {
    callback(getAjax());
}

function childfunction() {
    parentfunction(function(ajaxData) {
        //Do stuff with data
    });
}
Bob
+1 Callbacks are the way to go in such async scenarios.
Andreas Grech
A: 

The answer to your question is no.

In asynchronous requests, the function has to return before the result is available. To work around this, a callback pattern is used - when calling such a function, you don't expect a return, but rather provide it with a callback - a function to be called once the result is available.

Here's a simple example:

var someValue;
fetchValueFrom('http://example.com/some/url/with/value', function(val) { 
  someValue = val; 
  doSomethingElseWith(someValue);
});

Here we create a function and pass it in as a second param to the fetchValueFrom call. Once the value is available this function will be called, and will set the variable and call another function to continue execution.

levik