Use of Deferred Object in SharePoint Rest API

I have one issue in the project in which I have to update two lists item. Once first list item would updated then and then another list item would be updated. I have done Googling and get to know that we can handle two asynchronization call once first is executed. JavaScript API offers conecpt of Deferred Object which supports this type of functionality.

To communicate with SharePoint, developers mostly use SharePoint Rest API for better speed and performance.

The SharePoint Rest API can be used by inheriting the SP.RequestExecutor.js which available at the “…/_layout/15/” folder of SharePoint.

When there is requirement in which first asynchronous call is dependent upon another asynchronization call’s output at that time you can use concept of Deferred Object in JavaScript. For that we will need to control the calls sequences. But as we all know the fact that JavaScript is asynchronous and the flow of asynchronous calls cannot be controlled.

The JQuery Deferred object maintains an asynchronous call and it returns a Promise object when the call is complete.

The Promise object has two main methods to use,

done(fnSuccess, fnError, fnInProgress)
then(fnSucess)

I have created a small example of using JQuery Deferred object as shown below,

functionToCall().done(function (returnedValue) {
     // do something with the returned value or make another call here
});

function functionToCall() {
     var dfd = new $.Deferred();
     var executor;
     executor = new SP.RequestExecutor(appweburl);
     executor.executeAsync({ 
                             url: queryUrl, 
                             method: "GET", 
                             headers: {"Accept": "application/json; odata=verbose"},
                             success: onSuccess,
                             error: onError
                           });
     
     function onSuccess(data){
          var myVar = data.d.results;
          dfd.resolve(myVar);
     }

     function onError(data, errorCode, errorMessage){
          dfd.reject('Failed to load due to : '+errorMessage);
     }
return dfd.promise();
}

Additional things which needs to be consider while working with Deferred object:

  • Make sure the success and error handler are inside the async function so that the deferred object (dfd) remains global to them.
  • Both success and error handler should have deferred resolve and deferred reject methods.

Enjoy coading.. 🙂

Regards, Jay Doshi