Skip to content

Instantly share code, notes, and snippets.

@shrugs
Last active July 17, 2019 08:10
Show Gist options
  • Save shrugs/44cfb94faa7f09bcd9cb to your computer and use it in GitHub Desktop.
Save shrugs/44cfb94faa7f09bcd9cb to your computer and use it in GitHub Desktop.
google.script.run promise wrapper
// turns google.script.run into an object with a promise api
function scriptRunPromise()
var gs = {};
var ks = Object.keys(google.script.run);
for (var i=0; i < ks.length; i++) {
gs[ks[i]] = (function(k) {
return function() {
var args = arguments;
return Promise(function(resolve, reject) {
google.script.run
.withSuccessHandler(resolve)
.withFailureHandler(reject)
[k].apply(google.script.run, args);
});
}
})(ks[i])
}
return gs;
}
// USAGE:
var g = scriptRunPromise();
g.myServerMethod().then(function(result) {
// blah
})
.catch(function(e) {
// blah
})
@renoblair
Copy link

renoblair commented Dec 14, 2016

Just in case anybody still tries to get this to work, line 9 is missing the new operator when generating the promise.

return new Promise(function(resolve, reject) {

As an Angular service:

.service('GoogleScriptService', [function () {
  var keys = Object.keys(google.script.run);
  for (var i=0; i < keys.length; i++) {
    this[keys[i]] = (function (key) {
      return function() {
        var args = arguments;
        return new Promise(
          function(resolve, reject) {
            google.script.run
            .withSuccessHandler(resolve)
            .withFailureHandler(reject)
            [key].apply(google.script.run, args);
          }
        );
      }
    })(keys[i]);
  }
}])

Usage:

.controller('testCtrl', ['GoogleScriptService', function (GoogleScriptService) {
  var appsScript = GoogleScriptService;
  appsScript.myFunction()
  .then(resolveFunction)
  .catch(rejectFunction);
}])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment