Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make google.script.run looks a promise
// Converted https://gist.github.com/shrugs/44cfb94faa7f09bcd9cb for ES6
function scriptRunPromise() {
const gs = {};
// google.script.run contains doSomething() methods at runtime.
// Object.keys(goog.sscript.run) returns array of method names.
const keys = Object.keys(google.script.run);
// for each key, i.e. method name...
for (let i=0; i < keys.length; i++) {
// assign the function to gs.doSomething() which returns...
gs[keys[i]] = (function(key) {
// a function which accepts arbitrary args and returns...
return function(...args) {
// a promise that executes ...
return new Promise(function(resolve, reject) {
google.script.run
.withSuccessHandler(resolve)
.withFailureHandler(reject)[key]
.apply(google.script.run, args);
});
};
})(keys[i]);
}
return gs;
// gs.doSomething() returns a promise that will execulte
// google.script.run.withSuccessHandler(...).withFailureHandler(...).doSomething()
}
// usage with .then()
scriptRunPromise().doSomething().then((result) => {/* process result */}, (err)=>{/* handle err */});
// usage with async/await
async function foo() {
try {
const result = await scriptRunPromise().doSomething();
// process result
} catch(error) {
// handle error
}
}
@littell

This comment has been minimized.

Copy link

@littell littell commented Jul 8, 2020

Perfect, just what I was looking for!

@bekharsky

This comment has been minimized.

Copy link

@bekharsky bekharsky commented Sep 28, 2020

How can I pass user object? I am meaning withUserObject(). Just pass it along?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.