How to do sync in node js

I am trying to simply sync up a concatenated string that starts before the function and ends after the function. Please see the code snippet and simplify its output:



Any positive answer will be appreciated.

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


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>';




source to share

1 answer

You can use promises like Q to write synchronous look / feel / behavior of asynchronous code. With Q, you have to write above like

var str = '<=========';
var defer = Q.defer();
query1.on('result', function (row) {
  defer.resolve(row.company_name + ',');

  var str = "<=======" + + "====>";


You can also use the timeout technique. promises are better and are in the ES6 spec for integration with upcoming javascript.

As per the comments, there are more modern promises frameworks with more features. bluebird provides a nice way of promising existing features.



All Articles