Chaining ajax requests with jQuery's deferred

后端 未结 7 2394
天涯浪人
天涯浪人 2021-02-19 19:46

I have a web app which must call the server multiple times. So far, I had a long nested callback chain; but I would like to use jQuery\'s when,then etc

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 20:09

    I thought I would leave this little exercise here for anyone who may find it useful, we build an array of requests and when they are completed, we can fire a callback function:

    var urls = [{
        url: 'url1',
        data: 'foo'
    }, {
        url: 'url2',
        data: 'foo'
    }, {
        url: 'url3',
        data: 'foo'
    }, {
        url: 'url4',
        data: 'foo'
    }];
    var requests = [];
    var callback = function (result) {
        console.log('done!');
    };
    
    var ajaxFunction = function () {
        for (var request, i = -1; request = urls[++i];) {
            requests.push($.ajax({
                url: request.url,
                success: function (response) {
                    console.log('success', response);
                }
            }));
        }
    };
    
    // using $.when.apply() we can execute a function when all the requests 
    // in the array have completed
    $.when.apply(new ajaxFunction(), requests).done(function (result) {
        callback(result)
    });
    

提交回复
热议问题