javascript - 替代异步 : false ajax

标签 javascript jquery ajax

我循环遍历一个数组,为每个数组运行一个 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
});

关于javascript - 替代异步 : false ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22090764/

相关文章:

javascript - 在评论之前只抓取元素

javascript - 用php还是js显示数据?

javascript - 如何修改以下脚本以能够接收带空格的参数?

javascript - jQuery 在按钮单击时获取最接近的表单

javascript - 即使数据库连接已定义,Ajax 调用也会返回 Class 'db' not found 错误

javascript - 如何使用ajax laravel自动填写表单?

javascript - 如何使用 JavaScript 加密然后使用 C# 解密

jQuery 选择特定列中的特定单元格

javascript - youtube 视频结束时如何显示 Youtube 视频的最后一个屏幕?

javascript - AngularJS:装饰 $http