Home > Uncategorized > Using jQuery promises with SPServices

Using jQuery promises with SPServices

November 18th, 2013

I had reason to pull in data from three separate lists in SharePoint recently. Data in list three was dependant on lists one and two.

So I created an admin app page to manage problems with list three.  Having to pull data from all three lists, left me with some options

  • load them synchronously
  • nest the calls in successive succeeded function
  • Use jQuery promises

Perhaps someone has done this and there is a good example out there, but I couldn’t find it so I figured this out for me and am posting it because, well you can’t have enough examples.

This code is just enough of the original to demonstrate promises, I tested the original but had to change some details here which of course I havent had time to check, so I hope this works (it should with the lists in place) and give you enough insight.

In this code look at the $.when statement, the way I’m using it means that it will execute each function in turn and only continue if all functions suceed, if one fails it will execute the loadfailure function instead.

EDIT:As Marc comments below, SPServices returns a promise now so no need to build your own, see Marcs link
for more details. This code is still handy for seeing how to use promises with an async call, but this is not how to do it any more. This is quite messy code too.  When you start to use more structured code, SPA frameworks, then this method doesn’t really fit and the returned promise fits better with service or provider patterns unlike this jumble pattern here ;-).

 
<script language="javascript" type="text/javascript" src="js/jquery-1.7.min.js"></script>  
<script language="javascript" type="text/javascript" src="js/jquery.SPServices-0.7.1a.min.js"></script>  
<script language="javascript" type="text/javascript" src="js/underscore.min.js"></script>   
<div id="mainApp">
 <div id="appStatus">Initialising</div>
 <div id="appBody"></div>
</div>
<script>
var binaryJamPromisesTest = function ($) {
   
   	//Private Members
   
  	var listOne, listTwo, listThree;

	function main() {
		
		$("#appStatus").text("Loading");

		$.when(asyncGetListOne(), asyncGetListTwo())
		.fail(function() {
			loadFailure();
		})
		.done(function(){
			dataReady();
		});
  	}
  	
  	function loadFailure() {
	  	$("#appStatus").text("Failed to Load data");
  	}
  	
  	function dataReady() {
  		$("#appStatus").text("Processing Data");
  		
		//processLists();  //Do the main thread work here !
  	}
  	
  	
  	function asyncGetListOne() {
  	
  		var dfd = $.Deferred();
  		
		$().SPServices({          
			operation: "GetListItems",          
			async: true,          
			listName: "ListOne", 
			completefunc: function(data, status) { 
				if (status== "success") {
					_listOne=$(data.responseXML).SPFilterNode("z:row").map(function() 
	              	  		{ 
						return {
							id: $(this).attr('ows_ID'), 
				                        title: $(this).attr('ows_Title') 
	                			    }; 
			                 }); 
					dfd.resolve("");				
				}
				else
				{
					dfd.reject();
				}
			} 
		}); 
		
		return dfd.promise();

                
  	}

  	function asyncGetListTwo() {
  	
  		var dfd = $.Deferred();
  		
		$().SPServices({          
			operation: "GetListItems",          
			async: true,          
			listName: "ListTwo", 
			completefunc: function(data, status) { 
				if (status== "success") {
					_listTwo=$(data.responseXML).SPFilterNode("z:row").map(function() 
	              	  		{ 
						return {
							id: $(this).attr('ows_ID'), 
				                        title: $(this).attr('ows_Title') 
	                			    }; 
			                 }); 
					dfd.resolve("");				
				}
				else
				{
					dfd.reject();
				}
			} 
		}); 
		
		return dfd.promise();
  	}

	//Public Members
  	return {
   		init : main
  	}

}(jQuery); 


jQuery(function () {

    binaryJamPromisesTest.init();
});


</script> 
Categories: Uncategorized Tags:
  1. November 23rd, 2013 at 05:27 | #1

    Note that as of 2013.01, SPServices itself returns a promise, so there’s no need to do the wrapping you show here.

    See this post for examples:
    http://sympmarc.com/2013/05/08/jquery-library-for-sharepoint-web-services-spservices-2013-01-released/

    M.

  2. November 23rd, 2013 at 08:59 | #2

    I didn’t know that, thats a great enhancement. I’m glad I did this post still as an excercise in creating your own promises.

    I think I’ll look at incorporating built in spservice promises in the next post which builds on these past two and uses knockout.

Comments are closed.