我需要客户端代码等待被调用的服务器端(google.script.run)函数完成,然后再运行更多代码。
The withSuccessHandler(successFunc)
不会导致服务器调用之后的代码行等待。
我做了什么:
async function func(){
await google.script.run.withSuccessHandler(myFunc).serverFunc();
console.log("done");
}
func();
代码如何等待执行console.log
直到服务器端功能解决之后才行?
这个答案怎么样?请将此视为多个答案之一。
模式一:
在这种模式下,之后serverFunc
被运行,myFunc
正在运行。当时,console.log("done")
运行于myFunc
.
function myFunc() {
console.log("done");
}
function func(){
google.script.run.withSuccessHandler(myFunc).serverFunc();
}
func();
模式2:
在这个模式中,使用了 Promise。当你跑步时func()
,你可以看到ok
and 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();
Note:
- 如果您测试以上示例,请设置以下功能
serverFunc()
在 Google Apps 脚本端。
- 这是一个简单的示例脚本。所以请根据您的实际情况进行修改。
参考:
- 类 google.script.run
- withSuccessHandler(函数)
- 使用 Promise
如果这不是您想要的方向,我深表歉意。
Added:
如果您想使用来自的值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();
- 在此脚本中,返回值来自
myFunc
可以通过以下方式检索res
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)