0

I initialized two variables count and user, and I changed their value in the loop. Why does the function always return [0, 0] on finish?

Here's my code:

function getMonthSubs(month) { // month are the name of folders
    var cb = {count: 0, user: 0}, userTemp = [];
    readdir('./log/' + month, 'utf-8', function (err, files) { // files e.g. '2021_11_30.json'
        if (err) return [-1, -1]; 
        else {
            for (let j = 0; j < files.length; j++) {
                let temp = JSON.parse(readFileSync('./log/' + month + '/' + files[j], 'utf-8'));
                for (var key in temp) {
                    cb.count += temp[key].length;
                    if (!userTemp.includes(key)) {
                        userTemp.push(key);
                        cb.user++;
                    }
                }
            }
        }
    });
    return Array(cb.count, cb.user); // [0, 0]
}
Anotia
  • 11
  • 2
  • 2
    Are you sure readdir is synchronous ? If not that explains why the values are 0, because you might execute the return statement before entering the loop – Alex Nov 30 '21 at 15:51
  • Use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and you can await the result. It's not synchronous and returns the value immediately. – n1md7 Nov 30 '21 at 16:01

0 Answers0