javascript - for循环中的异步回调失败

标签 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 是一个执行异步调用并在回调中返回结果的函数。当我在单个项目上尝试此操作时,它工作得很好,但在循环内,当回调仍在发生时,循环会跳过并到达末尾,它会失败。

我还尝试了此解决方法,仅在回调成功中增加“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');
    }
  });

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

关于javascript - for循环中的异步回调失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45733100/

相关文章:

javascript - 如何查看浏览器是否支持CSS通用兄弟选择器~

php - 在发送到服务器之前如何操作表单数据?

javascript - 带路由的 Angular 安全身份验证

node.js - 如何从 MongoDB 集合中的数组中获取某个元素?

node.js - 在 Mongoose 中存储 "findOne"的值并使用 "find"插入返回值

javascript - 简单的 onclick 事件只工作一次

javascript - 直接分配.prototype进行类继承

javascript - 从 OpenShift Mongodb 保存文档

android - 在 Android 中,在进行 HTTP 调用之前测试 Internet 是否正常工作的最佳方法是什么?

c# - WCF 中的异步操作