Responsive Advertisement

SharePoint 2013: Implement Deferred And Promise Object In JavaScript Asynchronous Execute


SharePoint 2013 Client Object Model is used to retrieve, update and manage the data in SharePoint 2013 library/List. SharePoint makes an Object model available in several forms but here, we are using Javascript Object Model.

  • JavaScript library(JSOM)
  • REST/OData endpoints

In this Javascript Object Model, we will use executeQueryAsync() but it will execute/ will not wait for success/ fail to complete. We need to make executeQueryAsync() behave synchronously.
It means the function will wait for async operations, which should be completed and should return some values.

We know that SharePoint JavaScript Client Object Model is asynchronous. However, sometimes we want to process the things in a synchronous way.
This can be done by using JavaScript callbacks and deferred/Promises. Let's first see an asynchronous example, which we will later convert to synchronous:
For this reason, JavaScript is having an option to use deferred/promise method do this operation.


The promises pattern significantly simplifies JavaScript code when you make an app, which must have multiple, nested asynchronous calls and it makes it very powerful.


Your JavaScript code has to update multiple list items one by one to complete the basic operations and wait for the first one to execute.
However, Promise object also acts like a caching mechanism, where the success or failure function will be called immediately, if the Promise has already been fulfilled.
Promises object can make it easy to execute dependent asynchronous calls sequentially, which are based on the results.


The deferred/ Promise object is very simple syntax and powerful method for sequentially updating in the list/ list items.
Initially, we need to declare the deferred object, as shown below.

  1. var deferred = $.Deferred();  
At the end of the function, we have to return Promise object
  1. return deferred.promise();   
First, we will see about normal JavaScript execution.


For the method given above, we will get the output given below.
Execute second after retrieving the list items.
execute first
Here, we are expecting success function, which should execute first. Unfortunately, the previous one executed. Sometimes it will cause a major issue when you are updating the list items.
Thus, we need to use Async operation to perform synchronously.
Let's see the deferred/ Promise function, as shown below. 


For the code given above, we will get the output, as shown below.
execute first
Execute second after retrieving the list items

Post a Comment