简体   繁体   中英

Increment while loop on success of asynchronous google.script.run

I am trying to use google.script.run, the asynchronous client-side JavaScript API provided by Google Scripts within a while loop. I understand that calls to google.script.run are asynchronous so I even tried using a global variable 'window.i' for loop iterations.

Unfortunitely window.i++ never happens and the browser freezes when I run this code.

Here's the code snippet that I am struggling with:

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

Is there any way I can increment the loop variable on success callback?

Use the success handler to send the next request. Dont use a while loop.

//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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM