Sunday, June 21, 2015

How to use JQuery Deferred Objects in asynchronous operations for SharePoint JSOM

When we write SharePoint apps or client side logic in SharePoint pages, we may use asynchronous operations using JSOM or REST. As operations are asynchronous it is hard to control the flow of the execution. Apart from that we can make the situation even harder if we use nested asynchronous operations.

For an example I will read a web property using a REST call and the result is taken as an input to another REST call to read a list item.

Since my operations are asynchronous, how do I make sure that I enter to the second method once I return from the first method. It is difficult, right?

As a solution we can use JQuery Deferred objects. Following is a sample method to retrieve quick launch navigation links using deferred objects.

  1. function ReadNavigation() {
  2.     var def = $.Deferred();
  3.  
  4.     SP.SOD.executeOrDelayUntilScriptLoaded(function () {
  5.         var clientContext = new SP.ClientContext.get_current();
  6.         var quickLnch = clientContext.get_web().get_navigation().get_quickLaunch();
  7.         clientContext.load(quickLnch);
  8.  
  9.         clientContext.executeQueryAsync(
  10.             function () {
  11.                 var qlEnum = quickLnch.getEnumerator();
  12.                 var currentNav = [];
  13.                 while (qlEnum.moveNext()) {
  14.                     var node = qlEnum.get_current();
  15.                     var ob = {};
  16.                     var title = node.get_title();
  17.                     var url = node.get_url();
  18.  
  19.                     ob.title = title;
  20.                     ob.url = url;
  21.                     currentNav.push(ob);
  22.                 }
  23.                 def.resolve(currentNav);
  24.             }, function (sender, args) {
  25.                 def.reject("error");
  26.             });
  27.     }, "SP.js");
  28.     return def;
  29. }
  30.  
  31. ReadNavigation().done(function (nav) {
  32.     console.log(nav)
  33. }).fail(function (nav) { console.log("error!") })

2 comments:

user-asith said...
This comment has been removed by the author.
user-asith said...

Nice example
Q also good solution

https://gist.github.com/jeffcogswell/8257755