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:

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

      

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,
});

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

      

+1


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 + ',');
});

defer.promise.then(function(row){
  var str = "<=======" + row.company + "====>";
  console.log(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.

+1


source







All Articles