2

I want to update table rows with information from a Sharepoint list. So, I am calling executeQueryAsync within a For Loop and it only updates the last item, but not all.

var oRows= $('#dataTable tr');
for (i=0; i<oRows.length; i++) {
    var cCells = oRows[i].cells;        
    var oAISDelChoice = cCells[0].innerHTML
    var aAvailItemPromise = updateAvailabilityChoice(oAISDelChoice);
    aAvailItemPromise.done(function(oResult){
        cCells[1].innerHTML = oResult;
    });
}

function updateAvailabilityChoice(itemRef) {
   var oDeferred = $.Deferred(function() {
      var clientContext = new SP.ClientContext();
      var oList = clientContext.get_web().get_lists().getByTitle('Test Deliverables');
      var camlQuery = new SP.CamlQuery();
      camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Title\'/><Value Type=\'Text\'>' + itemRef + '</Value></Eq></Where></Query></View>');
      var AISDelList = oList.getItems(camlQuery);
      clientContext.load(AISDelList);
      clientContext.executeQueryAsync(
         function() {
            var listItemEnumerator = AISDelList.getEnumerator();
            while(listItemEnumerator.moveNext()) {
               oAISAval = "";
               var oListItems = listItemEnumerator.get_current();
               oDeferred.resolve(oListItems.get_item('DocType'));
            }
         },
         function() {oDeferred.reject(args);}
         );
    });
    return oDeferred.promise();
}
  • Doing this way will be complicated. But you can get all the list items from list on page load and save it in array. Then update the table cells based on choice selection in another cell. – Ganesh Sanap Nov 30 '18 at 16:40
  • Thanks, Ganesh - I was thinking of doing this initially. – Amrik Bhogal Dec 1 '18 at 6:54
  • Yes, that will be better performance wise. Making JSOM call on each selection will be overhead for application. – Ganesh Sanap Dec 1 '18 at 8:18
0

You can try to collect all promises into an array and wait for all of them to be resolved:

var promises = [];
for (i = 0; i < oRows.length; i++) {
    var cCells = oRows[i].cells;
    var oAISDelChoice = cCells[0].innerHTML
    var aAvailItemPromise = updateAvailabilityChoice(oAISDelChoice);
    promises.push(aAvailItemPromise);
    // aAvailItemPromise.done(function (oResult) {
    //     cCells[1].innerHTML = oResult;
    // });
}

// Wait for all promises to be resolved:
$.when(...promises).then( function(){
    var resolvedPromises=arguments; // The array of resolved objects as a pseudo-array
    for (i = 0; i < oRows.length; i++) {
        var cCells = oRows[i].cells;
        cCells[1].innerHTML = resolvedPromises[i];
    }
} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.