等待Google服务器端功能解决的最简单方法 [英] Easiest way to wait for google server-side function to resolve
问题描述
我需要客户端代码来等待被调用的服务器端(google.script.run)函数完成,然后再运行其他代码.
I need the client side code to wait for the called server side (google.script.run) function to complete before running any more code.
withSuccessHandler(successFunc)
不会导致服务器调用之后的代码行等待.
The withSuccessHandler(successFunc)
does not cause lines of code that are after the server call to wait.
我所做的:
async function func(){
await google.script.run.withSuccessHandler(myFunc).serverFunc();
console.log("done");
}
func();
在服务器端函数解析之后,代码如何才能等待执行 console.log
行?
How can the code wait to execute the console.log
line until after the server side function resolves?
推荐答案
此答案如何?请认为这只是几个答案之一.
How about this answer? Please think of this as just one of several answers.
在此模式下,运行 serverFunc
后,将运行 myFunc
.那时, console.log("done")
在 myFunc
中运行.
In this pattern, after serverFunc
was run, myFunc
is run. At that time, console.log("done")
is run in myFunc
.
function myFunc() {
console.log("done");
}
function func(){
google.script.run.withSuccessHandler(myFunc).serverFunc();
}
func();
模式2:
在此模式中,使用了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();
注意:
- 如果您测试上述示例,请在Google Apps脚本端设置
serverFunc()
的功能. - 这是一个简单的示例脚本.因此,请根据您的实际情况对此进行修改.
如果这不是您想要的方向,我深表歉意.
If this was not the direction you want, I apologize.
如果要使用 myFunc
上 serverFunc
中的值,那么以下示例脚本如何?
If you want to use the values from serverFunc
at myFunc
, how about the following sample script?
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();
- 在此脚本中,
res
可以检索从myFunc
返回的值. - In this script, the returned value from
myFunc
can be retrieved byres
.
这篇关于等待Google服务器端功能解决的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!