异步的替代方案: false ajax

2023-11-27

我循环遍历一个数组,为每个数组运行 ajax 请求。 我需要请求按顺序发生,这样我就可以接收最后一个请求并在成功时运行一个函数。

目前我正在运行(简化):

$.each(array, function(i, item){
    ajax_request(item.id, item.title, i);
})

function ajax_request(id, title, i){
    $.ajax({
        async: false,
        url: 'url here',
        success: function(){
            if(i == array.length-1){
                // run function here as its the last item in array
            }
        }
    })
}

但是,使用 async:false 会使应用程序无响应/缓慢。 但是,如果没有 async:false,有时其中一个请求会挂起一点,并在最后发送的 ajax 请求返回后实际返回。

我如何在不使用 async:false 的情况下实现这一点?


您可以使用本地函数来运行 ajax 调用,并且在每个连续的成功处理程序中,您可以启动下一个 ajax 调用。

function runAllAjax(array) {
    // initialize index counter
    var i = 0;

    function next() {
        var id = array[i].id;
        var title = array[i].title;
        $.ajax({
            async: true,
            url: 'url here',
            success: function(){
                ++i;
                if(i >= array.length) {
                    // run function here as its the last item in array
                } else {
                    // do the next ajax call
                    next();
                }

            }
        });
    }
    // start the first one
    next();
}

2016 年用一个使用 Promise 的选项更新了这个答案。以下是串行运行请求的方法:

array.reduce(function(p, item) {
    return p.then(function() {
        // you can access item.id and item.title here
        return $.ajax({url: 'url here', ...}).then(function(result) {
           // process individual ajax result here
        });
    });
}, Promise.resolve()).then(function() {
    // all requests are done here
});

以下是并行运行它们并返回所有结果的方法:

var promises = [];
array.forEach(function(item) {
    // you can access item.id and item.title here
    promises.push($.ajax({url: 'url here', ...});
});
Promise.all(promises).then(function(results) {
    // all ajax calls done here, results is an array of responses
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

异步的替代方案: false ajax 的相关文章

随机推荐