Answer the question
In order to leave comments, you need to log in
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();
Answer the question
In order to leave comments, you need to log in
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();
});
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 questionAsk a Question
731 491 924 answers to any question