Skip to content

Instantly share code, notes, and snippets.

@torufurukawa
Last active October 20, 2023 10:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torufurukawa/64339baf16efd3598e71dd763d1db0cf to your computer and use it in GitHub Desktop.
Save torufurukawa/64339baf16efd3598e71dd763d1db0cf to your computer and use it in GitHub Desktop.
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
Copy link

littell commented Jul 8, 2020

Perfect, just what I was looking for!

@bekharsky
Copy link

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