Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Last active Feb 24, 2021
Embed
What would you like to do?
Async-friendly google.script.run utility
/**
* Promise-friendly google.script.run call
* @param {String} funcName
* @param {...*} params
* @returns {Promise}
*/
const asyncGAPI = (funcName, ...params) => {
return new Promise((res, rej) => {
google.script.run
.withSuccessHandler(data => res(data))
.withFailureHandler(error => {
console.error(error);
rej(error);
})
[funcName].apply(null, params);
});
};
/**
* @typedef {{
* funcName : string,
* onFailure : function,
* onSuccess : function,
* params : array
* }} AsyncOptions
*
* @summary v2 of async-friendly google.script.run
* @param {AsyncOptions}
* @returns {Promise}
*/
const asyncGAPIv2 = ({
funcName,
onFailure = console.error,
onSuccess,
params = []
}) => {
return new Promise((res, rej) => {
google.script.run
.withSuccessHandler(data => {
typeof onSuccess === "function" && onSuccess(data);
res(data);
})
.withFailureHandler(error => {
typeof onFailure === "function" && onFailure(error);
rej(error);
})
[funcName].apply(null, params);
});
};
/**
* @summary mini-version of the above
* @param {string} funcName
* @param {...any[]} params
* @returns {Promise}
*/
const gscript = (funcName, ...params) => {
return new Promise((res, rej) => {
google.script.run
.withSuccessHandler(res)
.withFailureHandler(rej)
[funcName].apply(null, params);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment