Reputation: 4817
I'm using:
Currently the code works correctly, but I wonder if there is a way to avoid callbacks nested functions:
The queries:
/*************************
Queries
**************************/
var sql_states = 'SELECT ...';
var sql_colors = 'SELECT ...';
var sql_languages = 'SELECT ...';
/* ... more queries */
The execution of nested queries:
/*************************
Run queries
**************************/
db.query(sql_states).execute(function(error, r) {
if (error) {
req.session.error = 'Operation failed States';
res.redirect('back');
}
else if (r.length > 0)
{
for(var i in r){
states += '<option value="'+r[i]['id_state']+'">'+r[i]['name']+'</option>';
}
var colors = '';
db.query(sql_colors).execute(function(error, r) {
if (error) {
req.session.error = 'Operation failed Colors';
res.redirect('back');
}
else if (r.length > 0)
{
for(var i in r){
colors += '<option value="'+r[i]['id_color']+'">'+r[i]['name']+'</option>';
}
var languages = '';
db.query(sql_languages).execute(function(error, r) {
if (error) {
req.session.error = 'Operation failed Languages';
res.redirect('back');
}
else if (r.length > 0)
{
for(var i in r){
languages += '<option value="'+r[i]['id_language']+'">'+r[i]['name']+'</option>';
}
...
Any suggestions are welcome.
Thanks.
Upvotes: 1
Views: 657
Reputation: 4470
This is a typical problem in asynchronous JavaScript development. To be able to create a kind of serial execution path for you asynchronous functions there are various solutions that you should use for any medium to large project.
https://github.com/caolan/async
https://www.npmjs.com/package/promise
I do personally use async since I find it very well documented. You can easily solve your nested callbacks with an async.each constructs.
async.each(openFiles, function(file, callback) {
// do processing for every file and return callback when async call is completed
}, function(err){
// execute this piece of code when all your processing is complete.
});
Upvotes: 2