【发布时间】:2019-10-17 13:21:54
【问题描述】:
如何在 myFunc 真正结束后让这个 otherFunc() 运行?
async function func() {
const res = await (() => new Promise(r => google.script.run.withSuccessHandler((e) => r(myFunc(e))).serverFunc()))();
console.log(res);
otherFunc(); //this function still executed before myFunc end, except i use setTimeOut
console.log("done");
}
这是 myFunc() 内部的内容
function myFunc(){
var tbody = document.getElementById("table-permintaan");
var thead = tbody.firstElementChild;
while (tbody.hasChildNodes())
tbody.removeChild(tbody.firstChild);
tbody.appendChild(thead);
google.script.run.withSuccessHandler(function(nama){
dataArray.forEach(function(r){
justCreatingTableRows();
}).listNamaBarang();
}
}
这是 otherFunc() 内部的内容
function otherFunc(){
var btns = document.getElementsByTagName('button');
var mdls = document.getElementsByClassName("modal_detail");
var cds = document.getElementsByClassName("close_detail");
for(var i = 0;i<btns.length-1;i++){
btns[i].addEventListener("click",function(){
document.getElementById("mdl"+this.id.slice(3)).style.display = "block";
});
mdls[i].style.display = "none";
}
for(var i=0;i<cds.length;i++){
cds[i].addEventListener("click",function(){
for(var j = 0;j<mdls.length;j++){
console.log(this.id.slice(3) , mdls[j].id);
if (this.id.slice(3) == mdls[j].id.slice(3)) {
mdls[j].style.display = "none";
return;
}
}
});
}
}
使用 promise 并没有让 otherFunc() 在 myFunc() 之后运行,我仍然需要使用 setTimeOut,这对这种情况不利。
【问题讨论】:
-
我认为在你的脚本中,当
func()运行时,serverFunc()、myFunc(e)和otherFunc()按顺序运行。例如,您可以将myFunc()的脚本添加到您的问题中吗?我想确认一下您的情况。 -
我做了一些修改
-
您需要在所有
google.script.run调用中使用async-await。执行顺序:serverFunc()>myFunc()>otherFunc()。但是,myFunc()执行在function(nama)执行之前完成。 -
感谢您添加信息。关于
myFunc(),请像@TheMaster 的评论一样修改func()。作为其他观点,我认为myFunc()是不完整的。因为我认为由于语法错误,google.script.run.withSuccessHandler(function(nama){dataArray.forEach(function(r){justCreatingTableRows();}).listNamaBarang();发生了错误。dataArray是在其他地方声明的吗?请再次确认。
标签: javascript google-apps-script promise async-await