How to use $.when in jQuery with a chain of promises so that my ajax requests are executed in the correct order?
I have an array called costArray , which consists of several dynamic objects. For each element in this array, I will call an Ajax request called GetWorkOrder , which returns WorkOrder , which is basically a row element of the table with the .workOrder class, and adds it to the table with the identifier #tbodyWorkOrders .
Once all the elements of the array are processed, I use $.when to tell me when I can calculate SubTotal for each WorkOrder .
My problem is that my WorkOrder inserted into random orders, as ajax requests are handled by async. How can I ensure that my ajax requests are processed and added in the correct order?
i = 0; $.each(costArray, function (key, value) { var d1 = $.get('/WorkOrders/GetWorkOrder', { 'i': i }, function (html) { $('#tbodyWorkOrders').append(html); $('.workOrder').last().find('input').val(value.Subtotal); }); $.when(d1).done(function () { SetSubtotal(); i++; });
Edit:
costArray is taken from an earlier ajax call and is an array of elements that I insert in the rows of the table:
var costArray = JSON.parse([{"Trade":"Plasterer","Notes":"Test","Subtotal":"3781.00"}]);
Line:
$('.workOrder').last().find('input').val(value.Subtotal);
is one of many that takes values ββfrom GetWorkOrder and puts them in the correct input, but I did not use the extra code for clarity
source share