簡體   English   中英

如何在異步回調函數中中斷For循環

[英]How To Break A For Loop Inside An Asynchronous Callback Function

我正在嘗試打破異步回調內的嵌套for循環,但無法這樣做:

function asyncCall(id, OnComplete) {
    // id..
    context.executeQueryAsync(OnSuccess, OnFailure);

    function OnSuccess(sender, args) {
        OnComplete(userInGroup);
    }

    function OnFailure(sender, args) {
        console.error("Doesn't Exist!")
    }
}

function callApi() {
    //response from intial call
    for (var key in response) {
        var data = response[key];
        (function (innerData) {
            if (innerData) {
                renderHTML(innerData);
            }
        })(data);
    }
}

function renderHTML(data) {
    for (var key in data) {
        var index = data[key];
        (function (innerData, id) {
            asyncCall(id, function (isFound) {
                if (isFound)
                    break; //break loop
            });
        })(data, index);
    }
}

callApi();

我想打破循環,如果屬性isFound的值在響應中為true,並且只想在ES5中實現此目的,或者像同步調用之類的任何變通方法都可能有所幫助。

你不能

循環將在到達break之前完成。

唯一的方法是串行而不是並行運行asyncCall每次調用。 (例如,通過從傳遞給上一個回調函數的回調函數中調用下一個)。

正如Quentin所說,你不能。

但是,如果要防止發生進一步的回調,則可以設置一個變量,以防止發生回調。

let isFound = false;

function asyncCall(id, OnComplete) {
  // id..
  context.executeQueryAsync(OnSuccess, OnFailure);

  function OnSuccess(sender, args) {
      if(isFound) return;
      isFound = true;
      OnComplete(userInGroup);
  }

  function OnFailure(sender, args) {
      console.error("Doesn't Exist!")
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM