0

I would like to wait for the return of an .apply() execution that calls a function doing an AJAX operation. My code looks like this :

    //A function doing some AJAX stuff
    function f1(arg1, arg2) {
        $.ajax({
            type: "POST",
            url: "/some_url.php",
            data: "arg1="+arg1+"&arg2="+arg2,
            success: function(data) {
                if(data === "1")
                    return true;
                else
                    return false;
            }
        });
    }

    //Another function calling the first one
    function f2(arg1, arg2, other, things) {
        //What I would like to do
        if(f1.apply(null, [arg1, arg2]))
            doSomethingAwesome();

        //Continue code even if the AJAX isn't done yet
    }

The if(f1.apply(null, args)) doesn't wait for the ajax to be done, I understand that it is not supposed to do so, but is there a handler for the apply method ? I've made some test and the console.log() waits for the result, so I assume that there should be a way.

I read a bit about $.deferred and AJAX handler, however they always seem to be used inside the function that uses the AJAX. I also tried .complete() or .done() without success.

I really want to do the AJAX in another function because I will use it a lot with different purpose.

Insonore
  • 116
  • 6
  • AJAX is asynchronous, you can't wait for it to finish. – Barmar Jul 03 '17 at 09:50
  • Summary of the duplicate: `return $.ajax...` `doSomething().done(function() {});` Returning from the `success:` function does nothing as it's only scoped to that function (success callback). – freedomn-m Jul 03 '17 at 09:51
  • you'd have to build your own wait function - create a 'ajaxcallrunning' variable, set it to false. in ajax return function, set it to true. in function2, build a loop, that checks if variable is true, then run your logic and set variable to false. if variable is false, wait 1000ms and recheck... – errand Jul 03 '17 at 09:52
  • @errand please don't do that. Use async properly instead of hacking together workarounds. – Rory McCrossan Jul 03 '17 at 09:55
  • @RoryMcCrossan never said, that that would be a good solution :)) – errand Jul 03 '17 at 09:57

0 Answers0