google-apps-script - 如何同步调用google apps脚本服务器端函数?

标签 google-apps-script

我编写了一个谷歌应用程序脚本代码,它将打开一个谷歌电子表格,并按行列出值,但有两个问题: 1.按随机顺序输出。 2.将id为“loding”的div文本更改为“Finished!”在列出所有值之前。 我认为当我通过“withSuccessHandler()”运行脚本时,脚本会等待服务器端函数返回,但事实并非如此。 我该如何纠正它?

index.html:

<!DOCTYPE html>
<html>
    <head>
        <base target="_top">
        <script>
            function    jsListValue() {
                // Get count.
                google.script.run.withSuccessHandler(function(count) {
                    // List all values.
                    for( count; count>0; count=count-1) {
                        // Get a value.
                        google.script.run.withSuccessHandler(function(content) {
                            // Shows in "output".
                            var new_div = document.createElement("div");
                            new_div.appendChild(document.createTextNode(content));
                            document.getElementById("output").appendChild(new_div);
                        }).gsGetValue(count);
                    }
                    // Change loding notice.
                    document.getElementById("loding").innerHTML = "Finished!";
                }).gsGetCount();
            }
        </script>
    </head>
    <body onload="jsListValue()">
        <div id="output"></div>
        <div id="loding">Loding now...</div>
    </body>
</html>

代码.gs

function                doGet() {
    return HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function                gsOpenSheet() {
    // Return sheet of the note data.
    return (SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").getSheetByName("sheet1"));
}
function                gsGetCount() {
    // Return last row index in this sheet.
    return (gsOpenSheet().getLastRow());
}
function                gsGetValue(index) {
    // Return value in the (index,1).
    return (gsOpenSheet().getRange(index,1).getValue());
}

最佳答案

GAS 与 Javascript 非常相似,所有对 Google 服务器端函数的调用都是异步的。您无法更改此设置(至少我还没有看到任何文档注册)。

您可以做的是,在客户端使用回调函数来轮询服务器以获得“成功”返回值。它将继续轮询 1 分钟,否则退出。如果服务器返回成功值,则将客户端标志设置为“true”。除非标志为 true,否则客户端不应进行任何操作。通过这种方式,您可以控制客户端发生的事情。

关于google-apps-script - 如何同步调用google apps脚本服务器端函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37877433/

相关文章:

google-apps-script - Google Apps 脚本图表使用第 1 行作为标题

javascript - 使用 Google Apps 脚本进行 Stripe 付款

google-apps-script - 锁定预填充 URL 字段

wordpress - 有没有办法通过谷歌脚本在 WordPress 中添加帖子?

css - 放置 float 信息面板

for-loop - 替换列中的某些单元格值

javascript - 如何获得通过表单上传的文件的直接链接?

javascript - 如何从 Google Apps 脚本项目属性中存储和检索对象?

javascript - 在 Google Apps 脚本中打开对话框并关闭边栏

css - 使用 CSS 从谷歌应用脚​​本上传本地路径图像