【问题标题】:Ajax call to a MongoDB query in a JQuery each loop is affecting the order of results在 JQuery 中对 MongoDB 查询的 Ajax 调用每个循环都会影响结果的顺序
【发布时间】:2016-11-01 09:25:32
【问题描述】:

我正在尝试运行一个 AJAX 调用,该调用执行一个 mongoDB 查询并在每个循环中返回一个 JQuery 中的排序结果。排序后的数据库结果不会以正确返回的顺序附加到列表中。将has_users 设置为true 的某些结果附加到列表中的错误位置。如果我删除了对 AJAX/MongoDB 功能的 itemQuery() 函数调用,列表项将以正确的排序顺序附加。知道我做错了什么吗?

$.each(items, function (i, item) {
    //itemQuery() holds ajax call that runs mongoDB query and returns sorted results
    itemQuery(item._id).done(function(data) {
        if (data.length > 0) {
            has_users = true;
        } else {
            has_users = false;
        }

        listItem = buildListItem(item, has_users);
        $('#list_dropdown').append(listItem);
    });

}); 

【问题讨论】:

  • $.each 是同步的,所以所有的 Ajax 调用基本上都是一次启动的。元素按照 Ajax 调用接收响应的顺序附加,这不是确定性的。
  • 你不能创建一个json 列表并在一个ajax 请求中发送所有ID 吗?您使用此代码在服务器上产生大量流量,具体取决于项目的数量

标签: javascript jquery ajax


【解决方案1】:

某些 Ajax 调用在其他调用之前完成,因此您会得到错误的顺序。您可以使用$.map() 代替$.each(),返回一个Promise,然后使用$.when() 等待所有的promise 完成,然后追加元素。

您的代码可能是这样的:

$.when(
  $.map(items, function (i, item) {
    //itemQuery() holds ajax call that runs mongoDB query and returns sorted results
    return itemQuery(item._id).done(function(data) {
        if (data.length > 0) {
            has_users = true;
        } else {
            has_users = false;
        }

        return buildListItem(item, has_users);
    });
  })
).then(function (elements) {
  $('#list_dropdown').append(elements);
});

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多