user1167466
user1167466

Reputation: 333

Ajax Request Loop and Wait Until Complete

Is there a more efficient way to write the following? I need to loop through objList and pass the UnqKey to wfrmPrint. On success of that I then have to loop though the Pages. I am looping through the pages and unqkeys by passing a integer and checking to see if it is less than the length. I tried to use .when.apply taken from http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects, but it was loading the unqkeys and then the pages.

//sample objList
[
    {
        "UnqKey": 1,
        "Pages": [
            "wfrmSet1Page1.aspx",
            "wfrmSet1Page2.aspx"
        ]
    },
    {
        "UnqKey": 2,
        "Pages": [
            "wfrmSet2Page1.aspx",
            "wfrmSet2Page2.aspx",
            "wfrmSet3Page2.aspx",
            "wfrmSet4Page2.aspx"
        ]
    }
]

function Loop(iListIndex) {
var obj = objList[iListIndex];

if (iListIndex < objList.length) {
    jQuery.ajax({
        type: "GET",
        url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + obj.UnqKey, //load session that is used in wfrmSet1Pages.. or wfrmSet2Pages..
        success: function () {
            AddPages(obj, iListIndex, 0);
        }
    })
} else {
    alert('Done');
}
}

function AddPages(obj, iListIndex, iPageIndex) {
if (iPageIndex < obj.Pages.length) {
    jQuery.ajax({
        type: "GET",
        url: obj.Pages[iPageIndex] + '?Print=1', //load html 
        async: true,
        success: function (html) {
            iPageIndex++
            AddPages(obj, iListIndex, iPageIndex);
        },
        error: function () {
            alert('Failed!');
            iPageIndex++
            AddPages(obj, iListIndex, iPageIndex);
        }
    });
} else {
    iListIndex++
    Loop(iListIndex);
}
}

Upvotes: 1

Views: 1393

Answers (1)

Kevin B
Kevin B

Reputation: 95031

You might be able to do something like this,

function getData(arr,arrindex) {
    $.ajax({
        type: "GET",
        url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + arr[arrindex].UnqKey
    }).then(function(data){
        var deferredObj = $.Deferred(), defArr = $.map(arr[arrindex].Pages,function(page){
            return $.ajax({type: "GET", url: page + '?Print=1'});
        });
        $.when.apply(null,defArr).done(deferredObj.resolveWith).fail(deferredObj.resolveWith);
        return deferredObj.promise();
    }).done(function(){
        arrindex++;
        if (arr[arrindex]) {
            getData(arr,arrindex);
        }
        else {
            alert("done!");
        }
    }).fail(function(){
        alert("FAIL!");
    });
}
getData(objList,0);

It gets each wfrm sequentially, and when each one finishes, requests all of the pages for that one at once. Somewhat of a combination between your loop and a deferred $.when

Edit: fixed $.map argument order

Upvotes: 2

Related Questions