0

I am facing an issue related to the variable scope. Initially set "successCount" and "failedCount" variables as '0' and incremented that value after each success/failure iteration. But after the iteration got the initial value only for those variables.

var successCount = 0;
var failedCount = 0;
var counter = 0;
var data = {};
for (var i = 0; i < 5; i++) {
    updateField(data, (response) => {
        if (response.status) {
            successCount++;
        } else {
            failedCount++;
        }
    });
    counter++;
}

Accessing variable outside the loop

if(counter === 5) {
console.log(successCount);// Value is still 0
console.log(failedCount);//  Value is still 0
}

Any solution or what I am wrong with this code.

Thanks in advance

Varun Sreedharan
  • 517
  • 8
  • 28
  • Are you sure, the call is going inside the `updateField ` anonymous function? Can you also paste the how the response is coming `updateField` function – Sagar Chilukuri Feb 12 '20 at 09:46
  • you never define the variable cnt if I see it correctly. You have to check for the variable counter and not cnt. Give it a try :) – Aaron Feb 12 '20 at 09:47
  • @SagarChilukuri the response like { status: false, response: 'Failed/Success' } – Varun Sreedharan Feb 12 '20 at 09:48
  • Most likely `updateField` is asynchronous, see https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Teemu Feb 12 '20 at 09:53
  • This is not variable scope issue. This is due to node's asynchronous nature. You'll find many examples on how to work with asynchronous code in Node.js – tbking Feb 12 '20 at 09:53
  • See the solution in the [fiddle link](https://jsfiddle.net/#&togetherjs=ToH9ogIx8M). Its not the `variable scope` issue. Probably `updateField` function is throwing an error or you are not calling the callback function from `updateField` – Sagar Chilukuri Feb 12 '20 at 09:54

2 Answers2

1

Since the variables are updated in the callback you need to make sure that your console.log is not called before your callback.

You can try to convert your update function into a promise to be able to run the console log after all the function are resolved.

var successCount = 0;
var failedCount = 0;
var counter = 0;
var data = {};

function asyncUpdateField(data) {
    return new Promise((resolve) => {
        updateField(data, (response) => {
            if (response.status) {
                successCount++;
            } else {
                failedCount++;
            }
            resolve();
        });
    });
}
const promisesUpdateField = [];

for (var i = 0; i < 5; i++) {
    promisesUpdateField.push(asyncUpdateField(data));
}

Promise.all(promisesUpdateField).then(() => {
    console.log(successCount);// Value is still 0
    console.log(failedCount);//  Value is still 0
});
Benji
  • 53
  • 7
0

As it seems, the function updateField may be asynchronous. That's why your console.log() is being called before the execution of that function and at which point, value of successCount and failedCount is 0.

Plabon Dutta
  • 6,819
  • 3
  • 29
  • 33