简体   繁体   中英

Returning a var from inside 2 functions

Basically I need to to return a variable from inside of a function using an ajax call.

Like so:

function returnStuff(){
  $.ajax({
    //do stuff
  }).done(function(response){
    return response;
  })
return response;
}

I can't just use a variable in the done function and return that because the function will just return the undefined variable before the call completes.

Is there any way that I can return a variable through 2 layers of functions or is there a way that I can wait to return until the call is complete?

No. You cannot synchronously wait/block in JavaScript. Best you can do is something like this:

function returnStuff(){
  return $.ajax({
    //do stuff
  }).done(function(response){
    // handle some stuff
  });
}

returnStuff().done(function() {
    // add a 2nd event handler (called after the one above)
});

You have to rearchitect your code to not depend on getting a result back immediately.

Use jquery ajax async option. This will make the request blocking instead of asynchronous - note this can cause the UI to lock up while the request is happening, so I agree with Mark that you should change your code architecture to not require setting async false, however this does answer your question.

function returnStuff(){
    var ret;
    $.ajax({
       async: false,
       //do stuff,
       success: function(response) {
         ret = response;
       }
     });
     return ret;
}

Please note there is a really good write-up explaining why you should not do this here: How do I return the response from an asynchronous call?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM