Mak*_*ara 2 javascript web-applications promise google-apps-script async-await
我需要客户端代码等待被调用的服务器端(google.script.run)函数完成,然后再运行更多代码。
这withSuccessHandler(successFunc)不会导致服务器调用之后的代码行等待。
我做了什么:
async function func(){
await google.script.run.withSuccessHandler(myFunc).serverFunc();
console.log("done");
}
func();
Run Code Online (Sandbox Code Playgroud)
代码如何才能等到console.log服务器端函数解析之后才执行该行?
这个答案怎么样?请将此视为多个答案之一。
在此模式中,serverFunc运行之后,myFunc运行。那时,console.log("done")正在运行myFunc。
function myFunc() {
console.log("done");
}
function func(){
google.script.run.withSuccessHandler(myFunc).serverFunc();
}
func();
Run Code Online (Sandbox Code Playgroud)
在这个模式中,使用了 Promise。当你运行时func(),你可以看到ok和done是有序的。
function myFunc() {
return "ok";
}
async function func() {
await new Promise(r => {
google.script.run.withSuccessHandler(r).serverFunc();
});
const res = myFunc();
console.log(res);
console.log("done");
}
func();
Run Code Online (Sandbox Code Playgroud)
serverFunc()。如果这不是您想要的方向,我深表歉意。
serverFunc如果您想使用at中的值myFunc,下面的示例脚本怎么样?
function myFunc(nice) {
doStuffs(nice);
return "ok";
}
async function func() {
const e = await new Promise(r => {
google.script.run.withSuccessHandler(r).serverFunc();
});
const res = myFunc(e);
console.log(res);
console.log("done");
}
func();
Run Code Online (Sandbox Code Playgroud)
myFunc在此脚本中,可以通过 检索返回值res。