C
C
chrome1232015-04-09 13:11:22
Node.js
chrome123, 2015-04-09 13:11:22

How to make Node JS Execute code in order?

Good time of the day. Help solve the current problem. There is a code like this.

rez;
 connection.query('SELECT Некий запрос ', function(err, rows, fields) {
 if (err) throw err;
 for (var i=0; i < rows.length; i++) {

 rez = 'Записываем значение запроса'; 

connection.query("SELECT  ", function(err_photo, rows_photo, fields) {
if (err_photo) throw err_photo;

for(var k=0; k < rows_photo.length; k++){

rez +='Записываем значение 2 запроса';
console.log('1');
};
                                    
});

 console.log('2');

                        };
                    });

And so the code in this case is executed asynchronously. Because first console.log('2'); is written to the console. and only then console.log('1'); Please help me Make it so that the code is executed in order?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-04-09
@MarcusAurelius

Wrapping in https://github.com/caolan/async

async.series([
    function(){ /* выполнится первым */ },
    function(){ /* выполнится вторым */ }
]);

Y
Yuri Puzynya, 2015-04-09
@3y3

In support of Timur Shemsedinov 's advice , here's the code for you:

var async = require('async');

var queries = ['query_1', 'query_2'],
    result = '';

async.reduce(
  queries, 
  result, 
  function iterator(result, query, callback) {
    connection.query("SELECT  " + query, function(err_photo, rows_photo, fields) {
      if (err_photo) callback(err_photo);

      for (var k=0; k < rows_photo.length; k++) {
        result += 'Записываем значение 2 запроса';
        console.log('1');
      }

      callback(null, result);
    })
  },
  function done(error, result) {
    console.log(error, result);
  }
);

Also I ask you to format the code in your question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question