Last active
February 24, 2021 15:27
-
-
Save Oaphi/08c3e50ffb781fbebf8902756f46b551 to your computer and use it in GitHub Desktop.
Async-friendly google.script.run utility
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
/** | |
* 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