Last active
October 20, 2023 10:13
-
-
Save torufurukawa/64339baf16efd3598e71dd763d1db0cf to your computer and use it in GitHub Desktop.
Make google.script.run looks a promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
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
Perfect, just what I was looking for!