سؤال

I'm using the following function (code heavily removed for sake of pattern examination) to get all lists of a certain SP.ListTemplateType from a site collection. Since MS AJAX does not include a $promise function (to my knowledge), I'm creating a queue that increments as calls are made, and decrements as calls are returned, either successfully or in error.

This seems (possibly) prone to error, if the first call is returned before the second is made. So far, even in the case of 20+ recursions, the first call doesn't return until the last call is made, so the queue SEEMS to be safe.

Is this wrong, or am I doing this correctly?

function allListsOfType(type, callback) {
    //setup context, etc...

    var returnListArray = [];
    var queue = 0;

    getListsFromWeb(web);

    function getListsFromWeb(targetWeb) {
        //get lists from root web, and get all subwebs
        context.load(objects);
        queue++;

        context.executeQueryAsync(
            Function.createDelegate(this, function () { successHandler(); }),
            Function.createDelegate(this, errorHandler)
        );
    }

    function successHandler() {
        //add list results to array
        //loop through subwebs and call getListsFromWeb()
        queue--;
        if (queue == 0) {
            callback(returnListArray);
        }
    }

    function errorHandler(sender, args) {
        queue--;
    }
};

allListsOfType(SP.ListTemplateType.announcements, function(arr){
  alert(arr.length)
});
هل كانت مفيدة؟

المحلول

This seems correct, except that your callback will never be called if the first Ajax request returns an error.

Do the same check into errorHandler() than the one done into successHandler():

function errorHandler(sender, args) {
    queue--;
    if (queue == 0) {
        callback(returnListArray);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top