【问题标题】:Increment while loop on success of asynchronous google.script.run异步 google.script.run 成功时增加 while 循环
【发布时间】:2016-12-30 00:34:48
【问题描述】:

我正在尝试在 while 循环中使用 google.script.run, the asynchronous client-side JavaScript API provided by Google Scripts。我知道对 google.script.run 的调用是异步的,所以我什至尝试使用全局变量“window.i”进行循环迭代。

不幸的是,window.i++ 永远不会发生,并且当我运行此代码时浏览器会冻结。

这是我正在努力解决的代码 sn-p:

var iterations = 5;
window.i = 0;
while (window.i < iterations) {
    google.script.run
    .withSuccessHandler(function(){
        window.i++;
     })
     .sendNow();
}

有什么方法可以在成功回调时增加循环变量?

【问题讨论】:

  • 为什么要它异步成功处理程序?为什么不在外部和循环中增加它呢?因为 while 循环不会等待异步成功回调。它只会继续执行循环,最终你的浏览器会挂断
  • @kumkanillam 将立即触发所有请求。 sendNow() 的顺序很重要;在第一次运行后,仅处理剩余记录。

标签: javascript asynchronous google-apps-script web-applications


【解决方案1】:

使用成功处理程序发送下一个请求。不要使用while循环。

//these dont have to be global
var i = 0;
var iterations = 5;
function send() {
  google.script.run
  .withSuccessHandler(function() {
    i++;
    if (i < iterations) {
      send();
    }
  })
  .sendNow();
}

【讨论】:

  • 谢谢!我目前的配额用完了,所以无法测试。将在一天结束时使用这种方法进行一些测试并回复您。
  • 我用setTimeout测试过
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
相关资源
最近更新 更多