我正在编写一个具有对象数组的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是执行异步调用并在回调中返回结果的函数。当我在单个项目上尝试执行此操作时,效果很好,但在循环内失败,因为循环越过并到达结尾,而回调仍在进行。

我还尝试了这种解决方法,仅在回调成功中增加了“ i”。但它导致无限循环

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');
    }
}


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

最佳答案

尝试以下方法:

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');
    }
  });


但是,如果要链接请求,则应该摆脱循环

10-07 17:19