Wednesday, November 4, 2015

Using jQuery Deferred and Promises in SharePoint Hosted App

jQuery promises are awesome when you wanted to work with aysnc calls in SharePoint hosted app.

Below is the simple example to get the App web title in SharePoint 2013 using jQuery Promises.

 var def = $.Deferred();  
 $(document).ready(function () {  
   var promise = GetAppWeb();  
   promise.then(  
     function (result) { $('#message').text("The app web title is " + result) },  
     function (result) { $('#message').text("Error :" + result) }  
     );  
 });  
 var appContext;  
 var appWeb;  
 function GetAppWeb()  
 {  
   appContext = SP.ClientContext.get_current();  
   appWeb = appContext.get_web();  
   appContext.load(appWeb);  
   appContext.executeQueryAsync(onAppWebSuccess, onAppWebFailed);  
   return def.promise();  
 }  
 function onAppWebSuccess(sender, args)  
 {  
   var title = appWeb.get_title();  
   def.resolve(title);  
 }  
 function onAppWebFailed(sender,args)  
 {  
   def.reject(args.get_message());  
 }  

You can also use .done and .fail instead of .then function. The output of the above solution is as below


No comments:

Post a Comment