I am writing a Node JS function which have array of objects and for each item of it I need to call async function
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 is a function which executes async calls and return the result in the callback. when i tried this on a single item it worked perfectly but within the loop it fails as the loop step over and reach the end while the callback is still happening.
i also tried this workaround to only increase the ' i ' in the callback success. but it leads to infinite loop
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');
}
}
i wonder how to solve this and why this workaround failed.