javascript - NodeJS, mysql, and async results -


this question has answer here:

i'm using nodejs truncate list of 60 tables in database.

to this, i'm using 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; < tablelist.length; i++){     connexion.query('truncate '+tablelist[i]+';', function(err, rows, fields){         if(err) throw err;         console.log(i+'===> '+tablelist[i]+' truncated.')     });  } 

the problem output always:

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

i have 2 problems, tablelist array not accessible within callback function, , callback function keeps thinking i=60 correct value.

what doing wrong?

i have like:

0===> table0 truncated. 1===> table1 truncated. ... 

classic - async + loops not mix well.

you variable i. loops 0 tablelist.length - 1, , stops @ tablelist.length. each one, launch async request, callback.

now callbacks start hitting you, i tablelist.length, , tablelist[i] not exist. (tablelist accessible, being under closure; you're hitting past end due i having whatever value got left after loop ended.)

how solve? wrap contents of loop in iife, passing in loop counter (or values depending on loop counter) no bad effects closure closing on wrong thing:

for (i = ....) {   (function(i) {     ...   })(i); } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -