0

So I read several posts about how to do this like this and this, but I settled on something else that seems to work for this internal LOB application. I was having issues loading database dependencies asynchronously before loading an existing "allocation" (i.e., it was trying to load getAllocation(), getAssignedAssts() etc. before loading the depts, divisions, etc.) so I just put a second $.when/done call inside the doneCallback of the depencies. Like this:

// assume allocationID is defined as allocation id we want to get from db
$.when(getDept(), getDivisions(), GetAvailComments(), getTargets())
.done(function msg1, msg2, msg3, msg4) {
    // initialize variables, knockout observables and observable arrays

    $.when(getAllocation(allocationID), getAssignedAssts(allocationID), getAssignedTeachers(allocationID))
    .done(function msg1, msg2, msg3) {
    });
})
.fail(function jqXHR, textStatus, errorThrown) {
    alert('Error getting Allocation: ' + jqXHR.status + ' ' + textStatus + ', ' + errorThrown + '<br />' + jqXHR.responseText);
});

Assume getDept(), getDivisions(), etc. exist and return an ajax promise like this:

function getDept() {
    var data = { plan_id: getParameterByName('plan_id') };

    return $.ajax({
        type: "POST",
        url: "Plan_Edit.aspx/PlanDept",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
};

My question is whether this is bad, and if so, what is the "right" way to do this?

Community
  • 1
  • 1

1 Answers1

0

I Googled "jQuery nested when" and found this which I used as a starting point to rework into this jsfiddle. The code I've implemented above seems to be fine as shown with this example - the jquery calls in the second when/then are not called until the first set complete, which is exactly what I think I want due to the dependencies. Here's the javascript code:

function message(html) {
    $('<div/>').html(html).appendTo($('body'));
}

function process(){  
    $.when(a1(), a2()).done(function(){
    message('a1 and a2 complete');

    $.when(a3(), a4()).done(function(){
        message('a3 and a4 complete');  
    });
    });
}

function a1(){
    var dfd = $.Deferred();        
    setTimeout(function(){ message("a1 done"); dfd.resolve();  },4000);    // can use console.log or message
    return dfd.promise();         
}

function a2(){
    var dfd = $.Deferred();
    setTimeout(function(){ message("a2 done"); dfd.resolve();  }, 2500);
    return dfd.promise();
}

function a3(){
    var dfd = $.Deferred();
    setTimeout(function(){ message("a3 done"); dfd.resolve();  }, 3000);
    return dfd.promise();
}

function a4(){
    var dfd = $.Deferred();
    setTimeout(function(){ message("a4 done"); dfd.resolve();  }, 2000);
    return dfd.promise();
}

process();
Community
  • 1
  • 1