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.
- function ReadNavigation() {
- var def = $.Deferred();
- SP.SOD.executeOrDelayUntilScriptLoaded(function () {
- var clientContext = new SP.ClientContext.get_current();
- var quickLnch = clientContext.get_web().get_navigation().get_quickLaunch();
- clientContext.load(quickLnch);
- clientContext.executeQueryAsync(
- function () {
- var qlEnum = quickLnch.getEnumerator();
- var currentNav = [];
- while (qlEnum.moveNext()) {
- var node = qlEnum.get_current();
- var ob = {};
- var title = node.get_title();
- var url = node.get_url();
- ob.title = title;
- ob.url = url;
- currentNav.push(ob);
- }
- def.resolve(currentNav);
- }, function (sender, args) {
- def.reject("error");
- });
- }, "SP.js");
- return def;
- }
- ReadNavigation().done(function (nav) {
- console.log(nav)
- }).fail(function (nav) { console.log("error!") })
2 comments:
Nice example
Q also good solution
https://gist.github.com/jeffcogswell/8257755
Post a Comment