2016-12-30 53 views
1

我想在while循環中使用google.script.run, the asynchronous client-side JavaScript API provided by Google Scripts。我明白,調用google.script.run是異步的,所以我甚至嘗試使用全局變量'window.i'進行循環迭代。增量while循環成功異步google.script.run

不幸window.i ++從來沒有發生,當我運行此代碼時,瀏覽器凍結。

下面是我與掙扎的代碼片段:

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

有沒有什麼辦法可以增加成功的回調循環變量?

+0

爲什麼你想要它的異步成功處理程序?爲什麼不在外部和while循環中增加它?因爲while循環不會等待異步成功回調。它會繼續執行循環,最終您的瀏覽器將掛起 – kumkanillam

+0

@kumkanillam,它將立即啓動所有請求。 sendNow()是順序的,這很重要。因爲在第一次運行之後只處理剩餘的記錄。 –

回答

2

使用成功處理程序發送下一個請求。不要使用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(); 
} 
+0

謝謝!我目前沒有配額,所以無法測試。將在一天結束時使用此方法進行一些測試,然後回覆給您。 –

+0

我用'setTimeout'測試了它 – Kerndog73

+0

太棒了!這工作得很好! –