How to make code wait while calling asynchronous calls like Ajax

This question already has an answer here:

  • How do I return the response from an asynchronous call? 33 answers

  • Use callbacks. Something like this should work based on your sample code.

    function someFunc() {
    
    callAjaxfunc(function() {
        console.log('Pass2');
    });
    
    }
    
    function callAjaxfunc(callback) {
        //All ajax calls called here
        onAjaxSuccess: function() {
            callback();
        };
        console.log('Pass1');    
    }
    

    This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.


    Why didn't it work for you using Deferred Objects ? Unless I misunderstood something this may work for you.

    /* AJAX success handler */
    var echo = function() {
        console.log('Pass1');
    };
    
    var pass = function() {
      $.when(
        /* AJAX requests */
        $.post("/echo/json/", { delay: 1 }, echo),
        $.post("/echo/json/", { delay: 2 }, echo),
        $.post("/echo/json/", { delay: 3 }, echo)
      ).then(function() {
        /* Run after all AJAX */
        console.log('Pass2');
      });
    };​
    

    See it here .


    UPDATE

    Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

    Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.


    Real programmers do it with semaphores.

    Have a variable set to 0 . Increment it before each AJAX call. Decrement it in each success handler, and test for 0 . If it is, you're done.

    链接地址: http://www.djcxy.com/p/9476.html

    上一篇: JavaScript:Ajax请求后的全局变量

    下一篇: 如何在调用异步调用(如Ajax)时等待代码