Share via


SharePoint 2013: How to use Deferred when done in JSOM to make asynchronous to synchronous call

Introduction:

Here we will discuss how we can use Deferred with when in JavaScript Object Model to make a synchronous call in  SharePoint Online or SharePoint 2016/2013. In SharePoint 2013 client object model supports ExecuteQueryAsync and not synchronous ExecuteQuery. When you call ExecuteQueryAsync in JSOM on the client side, it executes the object model code you declared and carries on immediately. But sometimes you may require to do a synchronous call.

We can use Deferred when done in JavaScript Object Model in SharePoint 2013 to make call. Let us consider an example and then we will see how we can implement this.

Here let us take a list which has three columns:

  • Title
  • FirstName
  • LastName

And let us create an html form where user can enter title, first name and last name and click on submit button to save the data in the list and once the data get saved it should display in a div. So in this situation we need a synchronous call. Our Save to list code should execute first and once it is complete then our Retrive list items code should execute which will featch the data from list and show in a div.

So here we can use Deferred, when and done to achieve this. Below is the syntax:

Syntax:

$(function () { 
   
    $.when(addListItem()) 
       .done(function (data) { 
          retrieveListItems();
       }) 
       .fail(function (sender, args) { 
          // To do something 
       }); 
});

Here it will first addListItem() method and after it is done, then it will execute the retrieveListItems() method.

Here we have declared the Deferred() like below:

var dfd = $.Deferred();

Then we are returning the Deferred in the first method call. Also, we have called the resolve() and reject() method on the onSuccess and onFailure methods.

function onAddSucceeded(sender, args) {
    dfd.resolve(sender, args);
}
function onAddFailed(sender, args) {
    dfd.reject(sender, args); 
}

Full Code:

<h2>Add Items to Employee List</h2>
<div id="AddListData">
    <div>
        Title:
        <br />
        <input type="text" id="txtTitle" />
    </div>
    <div>
        First Name:
        <br />
        <input type="text" id="txtFirstName" />
    </div>
    <br />
    <div>
        Last Name:
        <br />
        <input type="text" id="txtLastName" />
    </div>
    <br />
    <div>
        <input id="btnSubmit" type="button" value="Submit" />
    </div>
</div>
<div id="divResult"></div>
<div id="divListItems"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var dfd = $.Deferred();
var listItemInfo = '';
$(function () {
    bindButtonClick();
});
 
function bindButtonClick() {
 
    $("#btnSubmit").on("click", function  () {
      
    $.when(addListItem()) 
       .done(function (data) { 
                 
          retrieveListItems();
           
       }) 
       .fail(function (sender, args) { 
          alert('Failed');
       });   
});
}
 
function addListItem() {
    var title = $("#txtTitle").val();
    var firstname = $("#txtFirstName").val();
    var lastname = $("#txtLastName").val();
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Employees');
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', title);
    oListItem.set_item('FirstName', firstname);
    oListItem.set_item('LastName', lastname);
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onAddSucceeded),
    Function.createDelegate(this, this.onAddFailed)
    );
    return dfd;
}
function onAddSucceeded(sender, args) {
    dfd.resolve(sender, args);
}
function onAddFailed(sender, args) {
    dfd.reject(sender, args); 
}
 
function retrieveListItems() {
    var clientContext = new SP.ClientContext();
    var oList = clientContext.get_web().get_lists().getByTitle('Employees');
    var camlQuery = new SP.CamlQuery();
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded),
    Function.createDelegate(this, this.onQueryFailed)
    );  
}
function onQuerySucceeded(sender, args) {
    listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '<strong>ID: </strong> '  + oListItem.get_id() +
        ' <strong>Title:</strong> ' + oListItem.get_item('Title') +
        ' <strong>FirstName:</strong> ' + oListItem.get_item('FirstName') +
        ' <strong>LastName:</strong> ' + oListItem.get_item('LastName') +
        '<br />';
    }
    $("#divListItems").html(listItemInfo);   
}
function onQueryFailed(sender, args) {
    alert('Hello');
}
 
</script>

Once you save the code and refresh the page, user can see a form. Let us enter the values in the field and click on Submit. It will show the list items like below:

https://www.enjoysharepoint.com/wp-content/uploads/2018/07/JavaScript_Object_Model_in_SharePoint_2013_synchronous.png

References:

You can check out few useful articles:

Conclusion:

Here we have discussed how to use Deferred when done in JavaScript Object Model in SharePoint 2013 to make asynchronous to synchronous call?