简体   繁体   English

jQuery异步调用顺序

[英]Jquery async calls in order

I'm new to Jquery and have some code which loops through an array and loads HTML from an ajax request on each iteration of the loop: 我是Jquery的新手,有一些代码循环遍历数组,并在每次循环迭代时从ajax请求中加载HTML:

$.each(arr, function (data) {
    $.get('/Quote/LoadQuoteItemCost', { 'i': i }, function (html) {
        $('#myTable).append(html);
        // There are a few more lines which modify the html which I've left out
    });
    i++;
});

My problem is that the responses are being appende to #myTable in random order, I assume due to the async nature of JQuery. 我的问题是,由于JQuery的异步特性,我认为响应是以随机顺序附加到#myTable的。 How can I ensure my responses are appended to my table in the order that they are iterated through the array? 如何确保我的响应按照遍历数组的顺序添加到表中?

I've tried async = false, but it's depreciated in my browser (and have seen many posts saying not to use it) 我尝试过async = false,但是在我的浏览器中已经贬值了(并且看到很多帖子说不使用它)

Here's how I'd do it using native (to some browsers) Promise 这是我将使用本机(对于某些浏览器)进行操作的方式

Promise.all(arr.map(function(data, i) {
    return $.get('/Quote/LoadQuoteItemCost', { 'i': i });
})).then(function(results) {
    results.forEach(function (html, n) {
        var data = arr[n];
        $('#myTable').append(html);
        ...
    });
});

jQuery's equivalent seems to be $.when , however, it accepts multiple (promise) arguments (rather than an array of Promises), and the then function receives multiple "results", rather than a single array of results - so the whole procedure would be a bit different from the "(almost) pure JS" above - but that should get you going jQuery的等效项似乎是$.when ,但是它接受多个(promise)参数(而不是Promises数组),并且then函数接收多个“结果”,而不是单个结果数组-因此整个过程将与上面的“(几乎)纯JS”有些不同-但这应该可以助您一臂之力

edit: I feel dirty doing it, but I'm fairly confident this will do what you want using more jQuery than I'm comfortable doing :p 编辑:我觉得这样做很脏,但是我相当有信心这会比我不喜欢的情况下使用更多的jQuery来完成你想要的:p

$.when.apply(null, $.map(arr, function(data, i) {
    return $.get('/Quote/LoadQuoteItemCost', { 'i': i });
})).then(function() {
    $.each(arguments, function (n, html) {
        var data = arr[n];
        $('#myTable').append(html);
        ...
    });
});

The concept I explained in the comments now in a fiddle and code: 我现在在小提琴和代码中在注释中解释的概念:

var responses = [],
    highestNumber = -1,
    highestReceivedNumber = -1;
function handleResponse(id, data) {
    highestReceivedNumber = Math.max(highestReceivedNumber, id);
    responses[id] = data;
    if(id===highestNumber+1)
        for(i=id;i<=highestReceivedNumber;i++)
            if(!responses[i]) return;
            else $('div:eq(0)').append(responses[i]) && highestNumber++;
}

take a look at this fiddle: http://jsfiddle.net/4udeg6wz/ 看看这个小提琴: http : //jsfiddle.net/4udeg6wz/

You should make other calls to the $.get in preceeding $.get's success call back recursively & maintain counter/variable to halt the recursion when your whole array 'arr' is consumed. 在$ .get成功之前,您应该对$ .get进行其他调用,并以递归的方式进行回调,并在整个数组“ arr”被消耗时保持计数器/变量停止递归。 This way the next $.get will only be initiated once the previous $.get's response has returned. 这样,只有在先前的$ .get的响应返回后,才会启动下一个$ .get。

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

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