简体   繁体   English

通过 JQuery 从循环中进行同步 Ajax 调用

[英]Making synchronous Ajax calls from a loop via JQuery

I've got the loop below in my code and each iteration calls a function in which there's an Ajax call.我的代码中有下面的循环,每次迭代都会调用一个函数,其中有一个 Ajax 调用。

I'm trying to find a way to make each iteration run only after the former iteration completed.我试图找到一种方法,使每次迭代仅在前一次迭代完成后运行。

Until now, as you can see, I've used a delay as a temporary solution.到目前为止,如您所见,我使用延迟作为临时解决方案。

Is there a neat way to make it synchronized?有没有一种巧妙的方法让它同步?

Thanks!谢谢!

$.each(matchIds, function(key,val){
        setTimeout(function(){
            gettingEvents(key, val,userID);
        },delay);
        delay+=1700;

    });

If they really are synchronous, then simply not using setTimeout will do the job.如果它们真的是同步的,那么简单地不使用 setTimeout就可以完成这项工作。

$.each(matchIds, function(key,val){
    gettingEvents(key, val,userID);
});

This is, however, a terrible approach that will tie up the JS event loop while all the requests run.然而,这是一种糟糕的方法,它会在所有请求运行时占用 JS 事件循环。 Use asynchronous requests instead.请改用异步请求。 Iterate inside the success handler instead of in an each loop.在成功处理程序中而不是在each循环中迭代。

var match_id_keys = Object.keys(matchIds);
var i = 0;
get_next();

function get_next() {
    if (!match_id_keys[i]) {
        return;
    }
    var key = match_id_keys[i];
    var val = matchIds[key];
    $.ajax( ... ).done(function () {
        // Do stuff with data
        i++;
        get_next();
    });
}

In 2020, we now have decent browser support for async and await which are tools for managing promises, so this can be written as a simpler loop:在 2020 年,我们现在asyncawait有了不错的浏览器支持,它们是管理 Promise 的工具,因此可以将其编写为更简单的循环:

async function get_all_ids(matchIds) { const entries = Object.entries(matchIds);异步函数 get_all_ids(matchIds) { const entries = Object.entries(matchIds); for (let i = 0; i < entries.length; i++) { const [key, val] = entries[i]; for (let i = 0; i < entry.length; i++) { const [key, val] = entries[i]; const data = await $.ajax(...); const 数据 = 等待 $.ajax(...); // Do stuff with data } } // 处理数据 } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM