Wait until all ajax requests are done

前端 未结 4 528
半阙折子戏
半阙折子戏 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条回答
  •  猫巷女王i
    2020-12-18 12:46

    No, you can't just loop like this: the callbacks would never get a chance to be called.

    I would do something like this:

    function translateAllFields(done) {
        var requestsInProgress = 0, doneCalled = false;
        translatable_fields.each(function () {
            ++requestsInProgress;
            $.ajax({
                //...
                success: function (data) {
                    //...
                    $("#ajacCounter").val(parseInt($("#ajaxCounter").val()) - 1);
                }
            }).always(function () {
                if (--requestsInProgress === 0) {
                    done();
                    doneCalled = true;
                }
            });
        });
        if (requestsInProgress === 0 && !doneCalled) {
            // in case translatable_fields was empty
            done();
        }
    }
    

    and then:

    $("#form").submit(function (e) {
        if (!(this).hasClass('ready')) {
            e.preventDefault();
            e.stopPropagation();
            translateAllFields(function() {
                $.ajax({
                    //validation
                    success: function (data) {
                        if (data['isValid']) {
                            $("#form").addClass('ready');
                            $("#form").submit();
                        }
                    }
                });
            });
        }
    });
    

提交回复
热议问题