-1

I'm currently using nodeJS to truncate a list of 60 tables in my database.

To do this, I'm using this code:

var mysql      = require('mysql');

var connexion = mysql.createConnection({
  host     : '1.1.1.1',
  user     : 'user',
  password : 'password',
  database : 'db'
});
connexion.connect();
var tableList = [
    'table0',
    'table1',
    'table2',
    ...
];
console.log('\n### Truncating tables... ###');
var i;
for(i = 0; i < tableList.length; i++){
    connexion.query('TRUNCATE '+tableList[i]+';', function(err, rows, fields){
        if(err) throw err;
        console.log(i+'===> '+tableList[i]+' truncated.')
    });

}

The problem is that the output is always:

60===> undefined truncated.
60===> undefined truncated.
60===> undefined truncated.
60===> undefined truncated.
60===> undefined truncated.
60===> undefined truncated.

I have two problems, the tableList array is not accessible within the callback function, and the callback function keeps thinking i=60 is the correct value.

What am I doing wrong?

I would like to have something like:

0===> table0 truncated.
1===> table1 truncated.
...
Vico
  • 1,696
  • 1
  • 24
  • 57

1 Answers1

0

Classic - async + loops do not mix well.

You get variable i. It loops from 0 to tableList.length - 1, and stops at tableList.length. For each one, you launch an async request, with a callback.

Now callbacks start hitting you, but i is tableList.length, and tableList[i] does not exist. (tableList itself is accessible, being under closure; you're just hitting past its end due to i having whatever value it got left with after the loop ended.)

How to solve? Wrap contents of the loop in a IIFE, passing in the loop counter (or values depending on the loop counter) so that you get no bad effects from your closure closing over the wrong thing:

for (i = ....) {
  (function(i) {
    ...
  })(i);
}
Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I could not find the right words to describe my problem and thus find this answer. Thank you for your help. – Vico Jun 01 '15 at 06:01