Thursday, November 23, 2017

Using ECMAScript 6 promises with JSOM

This is a small post for those of you that would be interested in using ECMAScript 6 promises with JSOM in SharePoint. A Promise represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Keep in mind that ECMAScript 6 might not be supported in all browsers. In that case, you could fall back to jQuery promises. If you want to use this in combination with EcexuteQueryAsync, you can. But you could also extend JSOM to provide a function that does this for you ...
You can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Extending JSOM
  SP.ClientContext.prototype.executeQuery = function (argument) {
    // Get a reference to this
    var that = this;
    // Create the promise
    var promise = new Promise(function (resolve, reject) {
      that.executeQueryAsync(
        function () { resolve(argument); }, 
        function (sender, e) { reject(e); }
      );
    });
    return promise;
  };

With that it is now easier to write something as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
$(document).ready(function () {
    getUser().then(
      function (user, folder) {
        $('#message').text('Hello ' + user.get_title());
      },
      function (e) {
        alert('Failed to get user name. Error:' + e.get_message());
      }
    )
  });

  // This function prepares, loads, and then executes a SharePoint query to get the current users information
  function getUser() {
    var user = context.get_web().get_currentUser();
    context.load(user);
    return context.executeQuery(user);
  }

No comments:

Post a Comment