Convert SharePoint JSOM's ExecuteQueryAsync to Promise in the Prototype

Today's blog is about adding an additional method to SharePoint JavaScript Object Model (JSOM)'s ClientContext object, so we can use it directly like a promise.

I call it "executeQuery" (instead of executeQueryAsync)

Wrapper with jQuery's $.Deferred

SP.ClientContext.prototype.executeQuery = function() {
   var deferred = $.Deferred();
   this.executeQueryAsync(
       function(){ deferred.resolve(arguments); },
       function(){ deferred.reject(arguments); }
   );
   return deferred.promise();
};

Wrapper with AngularJS's $q

SP.ClientContext.prototype.executeQuery = function() {
   var deferred = $q.defer();
   this.executeQueryAsync(
       function(){ deferred.resolve(arguments); },
       function(){ deferred.reject(arguments); }
   );
   return deferred.promise;
};

How do you use this?

var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
ctx.load(web);
var promise = ctx.executeQuery(); // look!  :-)

promise.done(function(){
  console.log(web.get_title());
});
promise.then(function(sArgs){
  //sArgs[0] == success callback sender
  //sArgs[1] == success callback args
}, function(fArgs){
  //fArgs[0] == fail callback sender
  //fArgs[1] == fail callback args.
  //in JSOM the callback args aren't used much - 
  //the only useful one is probably the get_message() 
  //on the fail callback
  var failmessage = fArgs[1].get_message();
});

This may seem to be just small syntactic sugar, but now you have JSOM returning a promise that you can chain, loop, combine and juggle to your heart's content!

Remember, jQuery.ajax, SPServices, AngularJS, and now JSOM all returns promise objects now.

2015 Xbox One Black Friday Edition

USA

Best Console Deals

http://deals.dell.com/compare/X500GOWFALLTD

$299
Gears of War: Ultimate Edition Bundle (that's 4 games) 
Fallout 4 (and Fallout 3 code next week) (that's 2 more games)
+extra controller
think this one is completely sold out.

http://www.bestbuy.com/site/microsoft-xbox-one-rise-of-the-tomb-raider-bundle-black/4512300.p?id=1219756880977&skuId=4512300

$349
Both Tomb Raiders.  (2 games)
Extra controller. 
1 TB HD (standard is 500 GB).

Xbox Live Gold

Buy 1 month for $1 from within the console.  Then buy 12 month for ~$30 via CDKeys.  Don't buy Xbox Live Gold monthly at $10/month. 

Gold is necessary for online play and you get up to 4 free games per month.  You need to go buy Xbox Live Gold.

EA Access

If you like EA's many games: Dragon Age, Battlefield, Titanfall, PvZ, Need for Speed, and their endless line of sports games.  Then pop down $30/year for EA Access all-you-can-eat pass.

Accessories

http://www.microsoftstore.com/store/msusa/en_US/list/categoryID.70508400?icid=XboxOneR_ModD_BFCM_WirelessControllers_112615

Multiple special controllers on sale.

Hard Drive

Standard console comes with 500GB.  This is not enough.  But Xbox One can use up to two more external harddrives at once.  I prefer 2TB Western Digital or Seagate portable harddrives - they can draw power from the XB1 directly and you don't need an extra plug.  Because of XB1's Hyper-V setup, external HD actually runs faster than internal HD.  These are regularly around US$65 and dropping.

Games

I buy Digital. 
http://majornelson.com/2015/11/26/black-friday-xbox-digital-game-deals/

There's extra discounts if you are an Xbox Live Gold member, which is $1 for this month.

Kinect, TV Tuner

If you are on the edge about whether you need these, pass.  They have their place and I love them, but Black Friday is about awesome deals and you can skip these.

 

Enabling LastPass bookmarklet with Microsoft Edge

One of the problems of Microsoft's Edge browser not supporting Extensions right now is that password management with tools like LastPass can be quite difficult.

Here is a workaround with LastPass via Bookmarklets

You need the help of another browser - either IE or Chrome. 
Because Edge doesn't currently have a way to create/modify bookmarklets

1. In IE/Chrome.  Login to your LastPass https://lastpass.com/index.php?ac=1

2. Browser down Tools > Bookmarklet

 

 3. In IE/Chrome.  Drag LastPass Fill! Into the Favourites Bar (IE) or Bookmark Bar (Chrome)
 4. In Edge, go to Settings > Show the favorites bar > On
 5. Import from another browser - choose either IE or Chrome
 6. In Edge.  Once import is complete, drag the bookmarklet into the Favourite Bar.  I also deleted other favourites that I didn't need from the import.

7. You now have a Lastpass bookmarklet!

 

Summary

This works for Twitter and Reddit

I also hope as Favourites gets synchronized across Universal Windows Devices - this should work on Xbox One and Windows Mobile 10 as well.

 

 

 

 

Thinking with JS Promise and Promises

 

Here's a real life example of a quick design iteration that we went through with promises this week.

In AngularJS (but this applies to any JavaScript), we have a function that calls the server to do a long running process.

function longProcess() {
    // dataservice returns a promise and we return that to our caller.
    return dataservice.longservice();
}

As this could potentially take nearly a minute, we want to add a waiting dialog.

AngularJS UI provides a modal dialog service $modal

function longProcess() {
  // create dialog
  var dialog = $modal.open({ templateUrl: 'wait.html' });

  var promise = dataservice.longservice();

  promise.then(
    function(){
      // success
      dialog.close();
    },
    function() {
      // fail
      dialog.close();
    }
  );
  return promise;
}

 

This works great.
But sometimes, the dialog flashes past too fast!  While the user is still trying to read it, it disappears.

Before we run off into code, let's stop a do a bit of thinking.

What we need is to combine the original promise, with a second new timer promise (of say 5seconds).  When both the service call has finished and the timer is up, we will resolve the promises.

So in pseudo code, it'd look like:

var p1 = service();
var p2 = $q.timer(5000);
var all = $q.all([p1,p2]);
all.then( /* resolve */ );

Note: $q is AngularJS' lightweight implementation of a Promise/A library Q.  The pseudo-code assumption was that $q would provide a timer-based promise that detonates once time is up.  In reality, $q doesn't provide such a method.  But the $timeout service in AngularJS returns a promise for exactly this scenario.

 

function longProcess() {
  var dialog = $modal.open({ templateUrl: 'wait.html' });

  var p1 = dataservice.longservice();
  var p2 = $timeout(angular.noop, 5000);
  var arrayOfPromises = [p1, p2];
  var promises = $q.all(arrayOfPromises);
  promises.then(
    function(){
      // success
      dialog.close();
    },
    function() {
      // fail
      dialog.close();
    }
  );

  // returns a combined promise to our caller.
  return promises;
}

 

Summary

The dialog opens and shows wait.html - it closes when the service is complete and when the timer has hit 5 seconds.  

 

 

Racing to the Races - Putting our Office App out there

As I'm posting this blog entry, our (SharePoint Gurus) first Office App (Add-In) would be available on the store.

I might let you in on a secret - it has in fact been in the store in the last few days, but as it is our company's first Add-In, we had some hiccups and had to push out subsequent updates.  We are pleased with this version and we'll run with it to the actual Melbourne Cup race, which actually isn't all that far away.  It would be on November 3, 2015, and the horses list would be available on October 31 - a Saturday, yes that means our Add-In would prompt you to automatically update data on Monday morning.

Feedback through the week from our clients has been very supportive.  This could turn out great (or a great learning experience).  But either way, we have fun and we hope our clients and friends have fun with our App too.

The Team

We are all consultants and this Add-In is something we wanted to build for a long time, but never could tear ourselves away from our great clients to just stop and write this Add-In.

  • We learn AngularJS along the way
  • We became pros at JavaScript Promises... chaining promises, grouping promises, catching error promises and retrying them.
  • Everyone in the company got involved.  We are not a large company, but this one Add-In has 100% contribution from the entire team.
  • We had different people deploying to their own developer sites, both On-Premises and Office 365. 
  • We use TFS but had an open checkout policy (you have to merge any changes).  This turned out not as disastrous as we think, it gave us freedom to work on the project when we can, without having to wait for a certain colleague to check in first.
  • We started the journey a long time ago with Wiki pages, Task lists and Yammer discussion group.  We are now on Office 365 OneNote (available anywhere, offline, and synchronized) and Office 365 Groups for conversation.  We use the Outlook Groups app when we are on the run.  If Office 365 Planner had been available, I'm sure we would be all over it too.  We had a white-board with moving tasks and Post-It notes.

The Stack

The Add-In is a SharePoint-Hosted App. 

Sweepstake Horse says SAAI.  Also, horse is sorry he didn't say on-premises

Sweepstake Horse says SAAI.  Also, horse is sorry he didn't say on-premises


The Learning (so far)

  • v2 will be provider hosted.  The complexity would lie in provisioning, and also not all our consultants are fluent with ASPNET MVC or C#
  • The benefits are to do with ease of updating the various components, and hiding core logic.
  • We may tackle NodeJS instead

You

You should download our Add-In and give it a whirl.  Come next Monday, hopefully we hear good things from you.

We already have people asking to do a Rugby World Cup one next year, which would have been fun, this weekend is finals between Australia vs. New Zealand.