我正在编写一个 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/