[Solved] Using jQuery deferred and promise inside loop


I think you can do something as simple as this:

var sortedArray = [AList, BList, CList, DList];

Promise.all(sortedArray.map(function(value) {
    var url = ...;
    return getListItems(url);
})).then(function(results) {
    // results is an array of results from AList, BList, CList, DList in order
    let allJsonData = [];
    results.forEach(function(approvedListItems) {
        allJsonData.push.apply(allJsonData, approvedListItems.d.results);
    });
    // process allJsonData here
});

// simplify getListItems like this
getListItems: function(url) {       
    return $.ajax({
        url: url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
},

The general idea here is that you get a raw list (without processing the sub-results inside of it) for each of the items in sortedArray. Using either Promise.all() or $.when(), you will get the raw lists in order. Then, after you have all the raw lists, you can process them in order and build your allJsonData structure in order.

Also, you can remove the promise anti-pattern from getListItems(). $.ajax() already returns a promise so there is no need to wrap it in another promise.

You could convert this to use $.when() instead of Promise.all() if you really wanted to, but it is more complicated to use $.when() because of how it takes arguments and returns results.

Also, there’s something wrong with the Javascript string syntax in your url variable. I don’t know what you intended to do there so I’m not sure what to suggest, but you need to fix that too.

2

solved Using jQuery deferred and promise inside loop