Reputation: 10634
I am writing a nodejs based script to take temperature readings from a raspberry pi and having some troubles with the Sequelize part where it adds the sensor to the database.
sensor.list
is used by the ds18x20 library to get all of the sensors connected to the raspi. I need to iterate through the results of this list function, and if the sensorId
doesn't exist in the database, i need to add it.
So far i have the following code, which retrieves the list of sensors, iterates over them and looks them up in the database..
sensor.list(function(e, sensors){
logger.debug("Sensors Found:");
logger.debug(sensors);
for(var i=0; i < sensors.length;i++){
db.Sensor.find({
where: { sensorId: sensors[i] }
}).success(function(s){
if (!s){
##sensors[i] is undefined here
logger.debug('Adding Sensor '+sensors[i]+' To the database as it doesn\'t exist!');
db.Sensor.create({
sensorId: sensors[i],
name: sensors[i]
});
}else{
Sensors.push(s);
}
});
}
});
Upvotes: 0
Views: 70
Reputation: 27855
Problem is that by the time the success callbacks starts triggering, i will have the value of sensors.length
.
You may approach it like
sensor.list(function(e, sensors){
/* This function returns the function which should
execute after callback with presnt i bound to it */
function GnBindCb(i) {
return function(s) {
if (!s){
##sensors[i] is undefined here
logger.debug('Adding Sensor '+sensors[i]+' To the database as it doesn\'t exist!');
db.Sensor.create({
sensorId: sensors[i],
name: sensors[i]
});
}else{
Sensors.push(s);
}
};
}
logger.debug("Sensors Found:");
logger.debug(sensors);
for(var i=0; i < sensors.length;i++){
db.Sensor.find({
where: { sensorId: sensors[i] }
}).success(GnBindCb(i)());
}
});
For more inputs about this issue, you can refer this post on Stackoverflow
.
Upvotes: 1