有人可以帮助控制谷歌脚本代码的流程。简单地说,我需要
google.script.run是HTML服务页面中可用的异步客户端JavaScript API,可以调用服务器端的Apps脚本功能。
但是,在我的情况下,我需要等到服务器函数返回其值。
谷歌脚本中的注意 No Promise()。
注意我尝试了许多回调混合但没有运气。
以下代码是从我的原生脚本&产生同样的错误。 我希望有以下日志:
第NUM行:1开始
行NUM:2,registerdProducts length = 1004
lineNUM:已检索到数据
第NUM行:4 Build UI
但我有不受欢迎的代码流,带有意外的日志
第NUM行:1开始
lineNUM:已检索到数据
第NUM行:4 Build UI
行NUM:2,registerdProducts length = 1004
最重要的影响:createRows
在其数据和数据的预制之前被调用。用户界面将不显示任何内容。
这是Javascript.html
代码:
<script>
var sheetId = "MyID";
var productsRange = "Variables!I2:I"
var registeredProducts =[];
function onSuccessDo(products){
/// assign the product list to the registeredProduct (global variable) .
registeredProducts=products;
console.log("line NUM:2, registerdProducts length = " , registeredProducts.length )
};
function createRows(){
/// This function will add the prodducts to the UI
console.log("line NUM:4, Build UI" )
for (var x in registeredProducts , x < registeredProducts.length , x++){
///Adding the product in rows.
}
}
function getProducts(){
/// This function will retrive the products from ths sheet & assign them to the global variable registeredProducts
console.log("line NUM:1, start")
var products = google.script.run.withSuccessHandler(onSuccessDo)
.getDataFromSheet( sheetId, productsRange);
console.log("line NUM: 3, Data has been retrieved")
};
document.addEventListener('DOMContentLoaded', function() {
getProducts();
createRows();
/// use registeredProducts in other functions
/// here
});
&安培;这是getDataFromSheet
中的Code.js
函数:
function getDataFromSheet(ID , range){
var sheet = SpreadsheetApp.openById(ID)
data = sheet.getRange(range).getValues();
for (x in data ){
if (data[x] == "" ){
delete data[x]
}}
return data;
}
答案 0 :(得分:1)
您有两种方式:
1)Server.gs
:
template = HtmlService.createTemplateFromFile('client.html');
template[some key] = 'some val';
2)
Javascript.html
<script>
var sheetId = "MyID",
productsRange = "Variables!I2:I",
registeredProducts = [];
function onSuccessDo(products)
{
registeredProducts = products;
console.log("line NUM:2, registerdProducts length = ", registeredProducts.length );
console.log("line NUM:3, Data has been retrieved");
createRows();
};
function createRows()
{
console.log("line NUM:4, Build UI");
for(var x in registeredProducts , x < registeredProducts.length , x++)
{
// code...
}
}
function getProducts()
{
console.log("line NUM:1, start")
google.script.run
.withSuccessHandler(onSuccessDo)
.getDataFromSheet(sheetId, productsRange);
};
document.addEventListener('DOMContentLoaded', function(){
getProducts();
});
</script>