The front-end development provides support to have a responsive UI, now exist very third-party libraries that help the developers. In this article I want to explain how is possible to use the javascript promises applied to JSOM (javascript object model) in SharePoint 2013, I used this particular topic in a project for a customer.

JSOM provides the possibility to retrieve information, fo​r example from a SharePoint list and to conduct the CRUD operations on it in asynchronous mode at all advantage of the UI.

However, in some cases is useful to wait the response of the call, for this support us the Deferred object of jQuery, in fact this object can storing a queue of callbacks and observe the success or failure state of any synchronous or asynchronous function.

Check this example present on the MSDN portal, obviously is necessary to do referencing at jQuery in the web page.

var siteUrl = '/sites/MySiteCollection';
var dfd = $.Deferred();

function retrieveListItemsInclude() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('100');
    this.collListItem = oList.getItems(camlQuery);

    clientContext.load(collListItem, 'Include(Id, DisplayName, HasUniqueRoleAssignments)');

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

function onQuerySucceeded(sender, args) {

    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
        
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() + 
            '\nDisplay name: ' + oListItem.get_displayName() + 
            '\nUnique role assignments: ' + oListItem.get_hasUniqueRoleAssignments();
    }

    dfd.resolve(listItemInfo.toString());
}

function onQueryFailed(sender, args) {
    dfd.reject(sender, args);
}

   //Now you can with a snippet of JavaScript code, check the status of the above:
   // When the function has finished...
   $.when(retrieveListItemsInclude())
      .done(function (data) {
         // To do something
      })
      .fail(function (sender, args) {
         // To do something
      });

for following the full sample please look my post on Code MSDN https://code.msdn.microsoft.com/Using-Promises-with-the-5558d5a8 and now enjoy with the code !