简体   繁体   中英

Ajax call to a MongoDB query in a JQuery each loop is affecting the order of results

I'm trying to run an AJAX call that executes a mongoDB query and returns sorted results within a JQuery each loop. The sorted database results do not get appended to a list in the correctly returned order. Some of the results that have has_users set to true are appended to the list in incorrect positions. If I remove the itemQuery() function call to the AJAX/MongoDB functionality, the list items are appended in the correct sorted order. Any idea what I'm doing wrong?

$.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);
    });

}); 

Some of the Ajax calls finish before the others, so you get wrong order. You can use $.map() instead of $.each() , return a Promise, and use $.when() to wait for all the promises to complete and then append the elements.

Your code could be something like this:

$.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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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