D
D
Danil2015-01-17 12:50:45
JavaScript
Danil, 2015-01-17 12:50:45

How to execute code synchronously in nodejs?

There is a code:

if (price) {
    connection.query('UPDATE fotopovtory SET price="' + price + '" WHERE foto_id = "' + itemId + '";', function(err, rows, fields) {
        if (err) throw err;
    });
}

if (type) {
    connection.query('UPDATE fotopovtory SET tipe="' + type + '" WHERE foto_id = "' + itemId + '";', function(err, rows, fields) {
        if (err) throw err;
    });
}
res.end();

The problem is that after the execution of the first if, res.end() occurs and the client script (having received the callback) updates the page, while only the changes in the first if are visible, since the 2nd if has not yet had time to finalize. Refreshing the page again - everything is fine. The question is how to execute res.end(); only after both calls to the database are completed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Shikanov, 2015-01-17
@Veneomin

You don't need to execute the code synchronously here. You just need to wait for 2 callback functions to be called and then execute res.end(). The easiest way to do this is with the async module :

var async = require("async");

// ...


var tasks = [];

if (price) {
    tasks.push(function(callback) {
        connection.query('UPDATE fotopovtory SET price="' + price + '" WHERE foto_id = "' + itemId + '";', callback);
    });
}

if (type) {
    tasks.push(function(callback) {
        connection.query('UPDATE fotopovtory SET tipe="' + type + '" WHERE foto_id = "' + itemId + '";', callback);
    });
}

async.parallel(tasks, function(err) {
    if (err) throw err;
    res.end();
});

A
Andrey Popov, 2015-01-17
@Nord001

Specifically, in this example, 0 or 1 query could be performed depending on the availability of data.
And res.end(); you now also, it seems to me, is not correctly located. If the request will be executed longer then it will not have time to be executed before res.end (); for good, in this case it should be called from the callback function.
If I understand everything correctly in NodeJS
Something like this:

if(price || type) {
  //составляем sql запрос, с 1 или 2 полями
    connection.query('UPDATE fotopovtory SET ....... WHERE foto_id = "' + itemId + '";', function(err, rows, fields) {
      if(err){
      res.writeHead(500);
      res.end();
      } else {
      res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
      res.end(results);
      };
    });
} else {
  res.writeHead(404);
  res.end();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question