Wait until all ajax requests are done

前端 未结 4 534
半阙折子戏
半阙折子戏 2020-12-18 12:11

I need to wait until all my ajax functions are done, and then continue the exectution.

My particular case is that I need to translate some fields in a form before su

4条回答
  •  难免孤独
    2020-12-18 12:54

    You can do this using deferred objects, but you do not need to use $.when.apply with an array if you are only interested in the final completion.

    Instead you can chain parallel promises using the pattern promise = $.when(promise, another promise)

    Change your translate to return the Ajax promise:

    function translate(...) {
        ...
        return $.ajax({
            ...
        });
    }
    

    and your promise loop simply becomes:

    var promise; // Start with an undefined promise - which is the same as a resolved promise for $.when
    translatable_fields.each(function() {
        promise = $.when(promise, translate(...));
    });
    
    // Wait for all promises to complete
    promise.done(function(){
        // now do the final code after all the ajax calls complete
    });
    

    Notes:

    • This does create an extra promise per call to $.when, but the overhead is very small and the resulting code is quite simple.

提交回复
热议问题