如何在异步回调函数中中断For循环

时间:2018-11-12 15:28:11

标签: javascript ecmascript-5

我正在尝试打破异步回调内的嵌套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中实现此目的,否则像同步调用之类的任何变通方法都可能会有所帮助。

2 个答案:

答案 0 :(得分:0)

不能。

循环将在到达break之前结束。

唯一的方法是在系列中而不是在 parallel 中运行asyncCall的每次调用。 (例如,通过传递给前一个回调函数的回调函数调用下一个)。

答案 1 :(得分:0)

正如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!")
  }
}