0

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked. more explanation would be appreciated to your answer demonstrating why this approach worked. i also have a question how i would determine that i reached the last callback in the thread ?
2

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++;
}

2 Comments

Thanks this also worked. i also have a question how i could determine that i reached the last callback in the thread ?
check the value of i should be equal to length-1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.