1

I know I can pass the callback function to access the value,looks like How to return value from an asynchronous callback function? but in my case , It need execute the synchronous method so i can do action outside the callback,any tip to help?

var foo;

function getFoo(callback) {
    $.ajax({
        url: url,
        async: false
    })
            .done(function(respond) {
        var data = respond.data;
        doStuff(data, function(respond) { //This is callback from Asynchronous function
            callback(respond);
        })
    });
}

getFoo(function(respond) {
    foo = respond;
});

return foo; //How can I access foo value from respond
Community
  • 1
  • 1
zhiJun
  • 31
  • 3
  • if `doStuff` is async then it won't work – Arun P Johny Aug 04 '14 at 10:55
  • 2
    also since `$.ajax()` in `getFoo()` is `async: false` you need to use the `success: function(){...}` callback format instead of `.done()` callback... see `As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success()` – Arun P Johny Aug 04 '14 at 10:57

1 Answers1

0

You can only return a value if the entire function is synchronous; in your case, doStuff is asynchronous, so you can't return foo like that (but it would be better to write the whole thing asynchronously anyway, since if you use jQuery's async: false option, it blocks the user interface until the AJAX result comes back).

Here's an example of how you could restructure your code:

function example(exampleCallback) { 
    function getFoo(callback){
        $.ajax({
            url: url
        })
        .done(function(respond) {
            var data = respond.data;
            doStuff(data,function(respond){ //This is callback from Asynchronous function
              callback(respond);
            })
        });
    }

    getFoo(function(respond){
        exampleCallback(respond);
    });
}

example(function(foo) {
    //do something with foo
});
Matt Browne
  • 12,169
  • 4
  • 59
  • 75