0

I wrote this code in node.js :

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('start\n');
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'hostname',
      user     : 'user',
      password : 'pass',
      database : 'dbname',
    });

    connection.connect();

    connection.query('SELECT code FROM user_type', function(err, rows, fields) {
      if (err) throw err;
            //This for is to run on all the results
            for(var i=0;i<2;i++){
            res.write('name:',rows[i].code);
        }
    });

    connection.end();

  res.end('End');
}).listen(8080);
console.log('Server running');

my questions are: 1. why did the res.write in the for loop print nothing in my html page? 2. what to write instead of 2 in the for?

1 Answer 1

3
  1. The issue is the timing of execution.

    Since connection.query() is asynchronous, it delays the execution of the callback function to when the query finishes, but allows the surrounding block of code to continue in the meantime. This results in res.end('End') being executed before res.write('name:',rows[i].code).

    To also delay res.end(), move it inside the callback:

    connection.query(..., function(err, rows, fields) {
        if (err) throw err;
    
        for (...) {
            res.write('name:',rows[i].code);
        }
        res.end('End');
    });
    
  2. rows should be an Array when there isn't an err, so you can use its length property:

    for (var i = 0; i < rows.length; i++) {
    

    It's also a common practice to store the value of length in a local variable:

    for (var i = 0, len = rows.length; i < len; i++) {
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.