异步回调for for循环失败

时间:2017-08-17 10:48:57

标签: javascript node.js asynchronous

我正在编写一个包含对象数组的Node JS函数,对于每个项目,我需要调用异步函数

for (var i = 0; i < allCases.length; i++) {

    if (allCases[i].Case_ID != null) {
        Utils.findAndUpdate(allCases[i], function(response) {
            console.log('received in the callback ', response);
        });
    } else {
        console.log('case id is null');
    }
}

findAndUpdate是一个执行异步调用并在回调中返回结果的函数。当我在一个项目上尝试这个时它完美地工作但是在循环内它会在循环结束时失败并在回调仍然发生时到达终点。

我也尝试过这种解决方法,只是增加了#39;我&#39;在回调成功。但它会导致无限循环

for (let i = 0; i < allCases.length;) {

    if (allCases[i].Case_ID != null) {
        Utils.findAndUpdate(allCases[i], function(response) {
            console.log('received in the callback ', response);
            i++;
        });
    } else {
        console.log('case id is null');
    }
}

我想知道如何解决这个以及为什么这个解决方法失败了。

2 个答案:

答案 0 :(得分:2)

请改为尝试:

allCases.forEach((case) => {
  if (case.Case_ID != null) {
      Utils.findAndUpdate(case, function (response) {
        console.log('received in the callback ', response);
      });
    } else {
      console.log('case id is null');
    }
  });

但是如果你想链接请求,那么你应该摆脱循环

答案 1 :(得分:2)

您可以使用IIFE;

for (let i = 0; i < allCases.length;) {

    if (allCases[i].Case_ID != null) {
        (function (i) {
            Utils.findAndUpdate(allCases[i], function (response) {
                console.log('received in the callback ', response);
            });
        })(i)

    } else {
        console.log('case id is null');
    }
  i++;
}
相关问题