在JQuery的每个循环中,Ajax调用MongoDB查询会影响结果的顺序
Ajax call to a MongoDB query in a JQuery each loop is affecting the order of results
我试图运行一个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);
});
});
一些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);
});
相关文章:
- 如何处理node.js节点mongodb中的连接和查询队列
- Mongodb数千个并行运行的查询
- 使用MEAN堆栈-查询MongoDB并将值作为变量传递
- MongoDB嵌套对象数组后查询
- 如何在mongodb中进行查询
- MongoDB collection.find()查询挂起
- 检查 mongodb 中是否存在项目(多个查询)
- 需要呈现MongoDB查询返回结果的特定索引/位置
- 使用计算值查询MongoDB
- 查询Mongodb时混合使用field和js函数
- 这是查询MongoDB的最佳结构吗?
- 查询MongoDB中不存在的字段
- 查询 MongoDB 删除触发器
- 我可以按日期查询MongoDB ObjectId吗?
- 使用nodejs查询MongoDb
- 如何在查询mongodb时将字符串值替换为斜杠
- 使用meteor查询mongodb集合中的子对象属性
- 查询mongodb中nodejs应用的总用户数
- 使用Express查询MongoDB服务器(Node.js项目)
- 在js中查询mongodb并将结果设置为变量