How to use deferred promise in SharePoint

Hello friends, in this article we are going to learn the usage of deferred promise in SharePoint. Many times we need to call a Rest API to fetch the list items and perform some actions based on the response. We write multiple javascript functions for the same and call them synchronously.

You know that javascript is synchronous(calls next function after the execution of previous) but when you want to call a Rest API, setTimeout, connection to the database, it works asynchronously. You can write async: false in the ajax calls which is not a good practice always.

To avoid using async: false every time in ajax calls, we have to use deferred promise.

Deferred Promise in SharePoint


Scenario

You have two functions (getListItem() and printItem()) in your javascript code. getListItem function is used to get the SharePoint list items. printItem function is used to print the item Title value in the browser console. 

In this case, if we call these two functions one after another without promise, printItem function might not receive the response at the time of execution because of the delay in the response and will fail to print the title.

Quick Answer

var Title = '';
function getListItem() {
    var dfd = $.Deferred();
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('TilesList')/Items(1)",
        type: 'GET',
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            Title = data.d.Title;            
            dfd.resolve();            
        },
        error: function(error) {
            alert(JSON.stringify(error));
        }
    });    
    return dfd.promise();      
}

function printItem(){
    console.log(Title);
}

getListItem().done(function(){
    printItem();
})

Description

We use deferred promise in SharePoint rest calls to wait for the script execution until we get the response from that rest call. In the above code snippet, 
  1. We have declared a Deferred object with a variable dfd. 
  2. when the actual response is obtained after a period of time, the promise object is said to be resolved.
  3. once we get the response from SharePoint, we are assigning the value of response to Title and resolving the deferred using dfd.resolve().
  4. dfd.promise() is returning the promise object of Deferred.
Thus getListItem().done(...) will understand that Deferred is resolved and promise is completed, so it will execute the printItem function.

Post a Comment

0 Comments