0

Is this possible to return value from function which includes an ajax call after the call is executed? For example, in the example here, function1 and function2 both have ajax calls. I'm forced to specify async as false for both the requests as the value that is returned from the functions is setup in the success callback. Is there anyway to overcome this issue so that calls can still be asynchronous but the return values are fine?

$(document).ready(function(){

    var abc = function1();
    var xyz = function2();
});


function1()
{
    var value = "";
    $.ajax({
          url: url,
          async: false,
          success: function(data) {
               value =  "value1";
          }})
    return value;
}


function2()
{
    var value = "";
    $.ajax({
          url: url,
          async: false,
          success: function(data) {
               value =  "value2";
          }})
    return value;
}
RKodakandla
  • 3,318
  • 13
  • 59
  • 79
  • call `function2()` in the `success:` of `function1()` – StudioTime Mar 15 '16 at 17:49
  • Asked before, and answered before, try this link. http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery – Alden Be Mar 15 '16 at 17:52
  • You can wait for both values to be assigned - I can't show you how as this has been marked as duplicate but that's the answer I think - I don't think this is a duplicate question fwiw – StudioTime Mar 15 '16 at 17:58

1 Answers1

0

You should process the asynchronously received data within the callback. Doing this synchronously is the bad way.

Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29