I have a beginners question regarding node.js / javascript syntax and asynchronous calls. I'm using node-dbi to pull some information out of a MySQL Server.
I have 2 tables. Client and Zone.
I need to write a function that does this:
for (i=0;<zone.count;i++){
for (j=0;j<client.count;j++){
//loop through the entire client table for each zone record & run a condition
}
}
Here is what my syntax in node-dbi looks like:
db.fetchAll('SELECT * from Zone', null, function(err, result){
if (result) {
db.fetchAll('SELECT * from Client', null, function(err, result){
if (result) {
//do something to all client records for each zone record
}
});
}
});
As it's immediately obvious, my result and err variables are clashing.. Can someone please explain the syntax to solve this asynchronous function?
Thanks!
Give each variable a name specific to that function:
db.fetchAll('SELECT * from Zone', null, function(zoneErr, zoneResult){
if (zoneResult) {
db.fetchAll('SELECT * from Client', null, function(clientErr, clientResult){
if (clientResult) {
//do something to all client records for each zone record
}
});
}
});
Also, you should refactor that a bit to make it more readable and remove that deep nesting.
Here's one way to think about it:
var getZones = function() {
var result;
db.fetchAll('SELECT * from Zone', null, function(zoneErr, zoneResult){
if (zoneResult) {
callback();
result = true; // assumes you need to keep track of success of failure of result
} else {
result = false;
}
}
return result;
};
var getClients { ... same code as above for clients };
getZones(getClients);
But that refactoring is off the cuff - it may not fit in your situation.
The problem should be solved by the first piece of code
Either rename the err and result into errZone,resultZone /errClient,resultClient as Squadrons suggested, or use async https://npmjs.org/package/async
// WARNING UNTESTED CODE
// npm install async
// or add async into your package.json dependencies
var async = require('async');
async.parallel({
zone: function (callback) {
db.fetchAll('SELECT * from Zone', null, function (err, result) {
if (err || !result) {
callback(err || 'No Zone results found', result)
}
});
},
client: function (callback) {
db.fetchAll('SELECT * from Client', null, function (err, result) {
if (err || !result) {
callback(err || 'No Client results found', result)
}
});
}
},
function (err, results) {
if (err) throw err;
for (var i = 0; i < results.zone.count; i++) {
for (var j = 0; j < results.client.count; j++) {
//loop through the entire client table for each zone record & run a condition
}
}
});