How to use Deferred when done in JSOM SharePoint

In this post we will see how we can use Deferred with when in JavaScript Object Model to make a synchronous call in SharePoint. As in many of the requirements we need to make asynchronous call to synchronous for easy of work. In the below example we will update multiple SharePoint list items one by one.

Code - 

var itemIDs = [1,2,3];

$(window).load(function() {

     $("#btnSubmit").click(function(){               

        $.each(itemIDs, function(index, value){              

            $.when(updateListItem(value))

       .done(function (data) {        

          alert("All Items Updated);            

       })

       .fail(function (sender, args) {

          alert('Failed');

    }); 

           });    

       });

  }); 


var dfd = $.Deferred();

function updateListItem(value) {

    var clientContext = new SP.ClientContext.get_current();

    var oList = clientContext.get_web().get_lists().getByTitle('Advisory Panel');


    this.oListItem = oList.getItemById(value);

    oListItem.set_item('Title', 'N/A');

    oListItem.update();

    clientContext.load(oListItem);  


    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));    

    return dfd;

}


function onQuerySucceeded(sender, args) {

    alert('Item updated!');

    dfd.resolve(sender, args);

}


function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());

    dfd.reject(sender, args);

}



The above code will update SharePoint list items whose ID's are stored in itemIDs array one by one. I hope you may implement Deffered in our any BAU requirement.

Comments

Popular posts from this blog

How to Customize exported excel's cell background color in Datatables

Populate dropdown using jquery ajax in SharePoint

Customizing SharePoint list and implementing Quick search using jQuery