5

There are more than 2000 objects in the rows array which need to be processed but got error Maximum call Stack exceeded.Callback function are manipulating database. I tried to use

setTimeout

that is working but making the execution slow. Is there any other method to fix it.

var updateRowsStatus = function (req, rows, next) {

    if (rows.length == 0) {
        return next();
    }

    var batchRows = rows.splice(0, 20);
    var count = 0;


    batchRows.forEach(function (row) {

       // other function 

        updateSubEntity(req, row, 'rows', function (err, response) {
            if (err)throw err;

            if (++count == batchRows.length) {

               updateRowsStatus(req, rows, next);

            }
        });
    });
};
Rohit
  • 2,987
  • 3
  • 25
  • 50
  • 2
    You're using a recursive function (one that calls itself). Can you think of a way to do the same processing without that pattern? – joews Apr 21 '15 at 08:15
  • Recursion or loop for handling db operations are always a bad idea. – Lewis Apr 21 '15 at 08:40
  • Please suggest best solution. – Rohit Apr 21 '15 at 08:41
  • You should ask another question with a tag related to your db type . If you're using MySQL, here is one of the solutions. http://stackoverflow.com/questions/18802671/update-multiple-rows-in-a-single-mysql-query – Lewis Apr 21 '15 at 08:45

1 Answers1

0

Someone posted this solution but removed. So i'm posting again his solution. Thanks to him.

    var count = 0;
    var length = rows.length;

    while (rows.length > 0) {

        console.log('rows -', rows.length);

        var batchRows = rows.splice(0, 20);

        batchRows.forEach(function (row) {
            updateSubEntity(req, row, 'rows', function (err, response) {
                if (err)throw err;

                if (++count == length) {

                    return next();
                }

            });
        });
    }
Rohit
  • 2,987
  • 3
  • 25
  • 50