Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Last active February 24, 2021 15:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/08c3e50ffb781fbebf8902756f46b551 to your computer and use it in GitHub Desktop.
Save Oaphi/08c3e50ffb781fbebf8902756f46b551 to your computer and use it in GitHub Desktop.
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