Mohamed A. Shebl
Mohamed A. Shebl

Reputation: 384

async Callback in for loop Fail

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.

Upvotes: 0

Views: 78

Answers (2)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

You can use 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++;
}

Upvotes: 2

Ivan Minakov
Ivan Minakov

Reputation: 1442

Try this instead:

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

But if you want to chain requests, then you should should get rid of cycles

Upvotes: 2

Related Questions