How to synchronize in node js

22 views
Skip to first unread message

Tarak Bhandary

unread,
Apr 23, 2015, 9:16:34 AM4/23/15
to nod...@googlegroups.com
I am trying to make it simply synchronize concatenated string which starts before the function and ends after the function. Please see the code snippet and make it simple to get the output like:

    <products>
    <proudct_name>Product1</product_name>
    <proudct_name>Product2</product_name>
    <proudct_name>Product3</product_name>
    </products>

Any positive reply will be appreciated.

    var mysql = require('mysql');
    var connection = mysql.createConnection({
          host     : 'localhost',
          user     : DB_USER,
          password : DB_PASS,
          database : DB_NAME,
    });
    
    connection.connect();
   
    var query = connection.query('SELECT * FROM tbl_product limit 0,3');
   
    var str = '<products>';
   
    query.on('result', function (row) {
        str += '<product_name>'row.product_name + '</product_name>';
    });
   
    str += '</products>';
   
    console.log(str);



Ryan Schmidt

unread,
Apr 23, 2015, 2:57:59 PM4/23/15
to nod...@googlegroups.com
Node will call the anonymous function you specified in "query.on('result', ..." when results come in, which will be asynchronously -- later -- after you've created and logged str.


You need to define a function, which accepts a callback parameter which the function will call when it has put together the full string. Here is an untested example:


function definition:


function getXml(cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : DB_USER,
password : DB_PASS,
database : DB_NAME,
});

connection.connect();

var str = '<products>';

var query = connection.query('SELECT * FROM tbl_product limit 0,3');

query.on('error', function (err) {
cb(err);
});

query.on('result', function (row) {
str += '<product_name>' + row.product_name + '</product_name>';
});

query.on('end', function () {
str += '</products>';
cb(null, str);
});
}


usage:


getXml(function(err, xml) {
if (err) throw err;
console.log(xml);
});


You would probably want to do the connection to the database outside of the function instead but I'm keeping it in since I don't know the structure of the rest of your application.

Note also that you'll want to escape row.product_name somehow. (Think about what would happen if row.product_name contained "<" or ">".)

Reply all
Reply to author
Forward
0 new messages