How to wait until nested async jQuery AJAX requests have finished?

后端 未结 2 953
傲寒
傲寒 2020-12-18 07:05

I\'m using jQuery and I have a loop of asynchronous AJAX requests. I know I can wait for them all to be finished by using the handy \'$.when.apply(array_of_requests).then()\

相关标签:
2条回答
  • 2020-12-18 07:50

    Try this with only one main promise to fullfill (resolve) per loop-run (here still called inner_promise).

    var initial_data = [1,2,3,4,5,6,7,8,9,10];
    var promises_inner = [];
    
    initial_data.forEach(function(n) {
        // Create promise for the inner call here.
        var promise_inner = $.Deferred();
        promises_inner.push(promise_inner);
    
        $.ajax({url:'http://www.domain.com/etc/'+n}).done(function(data) {
            $.ajax({url:'http://www.domain.com/etc/'+data.result}).done(function(data) {
                // Do something with the content of data here.
                promise_inner.resolve();
            });
        });
    });
    console.log("promises_inner contains " + promises_inner.length + " promises") // should contain all the 10 promises
    
    $.when.apply($,promises_inner).done(function() {
        // The inner AJAX calls are finished now
    })
    
    0 讨论(0)
  • 2020-12-18 07:57

    Take a look at $.Callbacks in 1.7. I think you'll be excited about the flexibility of making your own "flows" and the ability to reuse them, run once, etc.

    There's nothing wrong with what you did (the apply pattern may not be a first choice of most, they usually just list them in a $.when(a, b, c....)--but you may like the syntax of $.Callbacks better.

    0 讨论(0)
提交回复
热议问题