connection.query('select * from `test` WHERE `deny`=false',function(err,rows,fields){
for (var i=0; i<rows.length; i++){
if (rows[i].enddate == mydate)
{
msg = "message";
connection.query('select * from `cash` WHERE `id`=test',function(err2,rows2,fields2){
if (rows2[0].cash >= 30)
{
connection.query('UPDATE `cash` SET `cash`='+ rows2[0].cash-30 +' WHERE `id`=test',function(err3,rows3,fields3){
msgsend(rows[i].contact,msg);
});
}
});
}
}
});
This is my code.
However, when I run my code
It shows an error like this:
TypeError: Cannot read property '0' of undefined
Please help
What is wrong with my code?
Try Debugging it firstly using
console.log(rows) and console.log(rows2) may be one of them is empty.
Also the error parameters are for reason ,you could catch error parameters and check them:
if(err) console.log(err)
else //rest of program
Similarly err2
if(err2) console.log(err2)
else //rest of program
This will definetly help in solving the issue
EDIT
Where do you put debug line??
Obviously where you have to debug
Like
function(err,rows,fields){
console.log(rows); //undefined if empty
if(err) console.log(err);
else //rest code
}
Have you tried Async
connection.query('select * from `test` WHERE `deny`=false',function(err,rows,fields) {
for (var i=0; i<rows.length; i++){
if (rows[i].enddate == mydate) {
myFuntion(row[i], function(msg) {
console.log(msg) // Success!
})
}
}
})
function myFuntion(row, callback) {
async.waterfall([
function(callback) {
msg = "message";
connection.query('select * from `cash` WHERE `id`=test',function(err2,rows2,fields2){
callback(null, rows2);
});
}, function(rows2, callback) {
if (rows2[0].cash >= 30)
{
connection.query('UPDATE `cash` SET `cash`='+ rows2[0].cash-30 +' WHERE `id`=test',function(err3,rows3,fields3){
msgsend(row.contact,msg);
callback(null);
});
}
}
], function(err){
if(err)
console.log("Error: ", err);
else
callback("Success!");
})
}
Related
app.get('/',function (req,res) {
client.getAllOffers(null,function(err, resp) {
if (!err) {
offer = JSON.parse(resp);
test1 = offer.allOffersList.length;
res.send(offer);
for(var i=0;i<test1;i++) {
var stmt = "INSERT INTO offers(description,start_time,end_time) VALUES (?, ?, ?)";
connection.query(stmt, [offer.allOffersList[i].description, offer.allOffersList[i].startTime, offer.allOffersList[i].endTime], function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});
}
}
else {
console.log(err);
}
});
});
In this case i'm having function in getAllOffers in the second line of the code.
If I encounter an error how can I recall the function untill I get the response.
How I will be done?
You can do this recursively by wrapping the getAllOffers call in a function. I would recommend putting a limit to the number of retries to prevent an infinite loop.
const getAllOffers = function(callCount) {
if(callCount < 5) {
client.getAllOffers(err) => {
if(!err) {
console.log('yay!');
else {
getAllOffers(++callCount);
}
}
}
}
getAllOffers(0);
I have been on this for a good few hours.
I have the below function which reads from a table in my postgres db. It works as expected if there is stored strings in a column.
I can't get the 'else if' statement to work when there is no string in a field. To test this out I have a completely empty column under brand_code and its still executing the 'else' statement.
Now, I know why. There are 3 rows in the table. When I change the else if to === 3, it works as I'd like.
What code do I need to make the 'else if' statement work if the field is empty? (I plan to expand the SELECT statement later).
readCodes: function(callback) {
var pool = new pg.Pool(config.PG_CONFIG);
pool.connect(function(err, client, done) {
if (err) {
return console.error('Error acquiring client', err.stack);
}
client
.query(
'SELECT brand_code FROM public.voucher_codes',
function(err, result) {
if (err) {
console.log(err);
callback('');
} else if (result.rows.length === 0 ) {
console.log(result);
callback('');
} else {
let codes = [];
for (let i = 0; i < result.rows.length; i++) {
codes.push(result.rows[i]['brand_code']);
}
callback(codes);
};
});
});
}
}
Really struggled with this all day so any help is appreciated.
I am still learning. Prior to last week, I have never coded so apologies if this is amateur hour.
The problem here is that you are checking if it has returned rows or not, what you need instead is to check in each row if the field is empty
I suggest using underscore for iterating over each row:
_.each(result.rows,function(element, index){
if(element['brand_code'].length != 0){
codes.push(element['brand_code'])
}else{
console.log('empty field # results['+index+']')
}
})
CODE :
readCodes: function(callback) {
var pool = new pg.Pool(config.PG_CONFIG);
pool.connect(function(err, client, done) {
if(err){return console.error('Error acquiring client',err.stack);}
client.query(
'SELECT brand_code FROM public.voucher_codes',
function(err, result) {
if (err){console.log('[!] Error:',err); callback('');}
else if(result.rows.length == 0 ){
console.log('[!] Error:','No rows returned!');
callback('');
} else {
let codes = [];
_.each(result.rows,function(element, index){
console.log(element , index)
if(element['brand_code'].length != 0){
codes.push(element['brand_code'])
}else{
console.log('empty field # results['+index+']')
}
})
callback(codes);
}
});
});
}
How would you stop the rest of the code from executing in NodeJs (not termine the application with process.exit() just say this is the last line to be executed).
In regular javascript you have exit(), but that doesnt seem to work in nodejs.
Below is the situation:
connection.query(sql, [req.session.sessionUserPackagePassword] , function(err, rows, fields) {
if (!err) {
var userFound = false;
for(var i=0; i< rows.length; i++) {
// Make the comparaison case insensitive
if ((rows[i].deliveredToUser).toLowerCase() == `no`) {
userFound = true;
console.log(userFound);
[...]
}
}
if (!userFound) {
res.render('pickup/errorAlreadyDelivered', {});
// exit here
}
console.log(userFound);
// If the query fails to execute
} else {
console.log('Error while performing Query.');
res.render('errorConnection', {});
}
});
connection.end();
// Update the query to say the box has been delivered to user and specify time
// Establish the connection
[...]
res.render('pickup/openPackageClose', {
title: '',
helpButtonURL: '/help/help-dropPackage',
helpButtonTitle: 'Help'
});
});
Essentially when this condition is met, I would like the rest of the code not to be executed
if (!userFound) {
res.render('pickup/errorAlreadyDelivered', {});
// exit here
}
connection.end(); then return; seems like it might work for you.
So based on your comment on my other answer, it sounds like your program structure isn't what I thought it was. This should work:
connection.query(sql, [req.session.sessionUserPackagePassword] , function(err, rows, fields) {
if (!err) {
var userFound = false;
for(var i=0; i< rows.length; i++) {
// Make the comparaison case insensitive
if ((rows[i].deliveredToUser).toLowerCase() == `no`) {
userFound = true;
console.log(userFound);
[...]
}
}
if (!userFound) {
res.render('pickup/errorAlreadyDelivered', {});
connection.end();
} else {
console.log(userFound);
console.log('Error while performing Query.');
res.render('errorConnection', {});
connection.end();
}
I've been trying to diagnose this bug for some time now but can't figure out why my completed() function executes before all my asynch functions are done. I'm using the async library:
async.forEach(data.DBInstances, function (dbInstance, fcallback) {
let dbtype = dbInstance.Engine;
let logFilename = log[dbtype].log();
let instanceId = dbInstance.DBInstanceIdentifier;
if (tagFilter) {
let arn = dbInstance.DBInstanceArn;
checkRDSTag(arn, tagFilter, function (err, found) {
if (!err) {
//tag was found, continue processing and check other filters...
if (found) {
if (noFilter || (instanceTypes && instanceTypes.indexOf(dbtype))) {
//console.log('db type is: ' + dbtype);
processOrCreateLog(instanceId, dbType, function (err, data) {
if (!err) {
console.log("Data: " + JSON.stringify(data));
completed.push(data);
fcallback(null);
} else {
cb(err, null);
}
});
}
} else {
//tag wasn't found but was specified, don't process anything...
console.log("tag specified was not found on instance: " + instanceId);
}
} else {
console.log("Error checking RDS Tag");
cb(err, null);
}
});
}
//only process filtered types...
else if (noFilter || (instanceTypes && instanceTypes.indexOf(dbtype))) {
console.log('db type is: ' + dbtype);
processOrCreateLog(instanceId, dbtype, fcallback, function (err, data, fcallback) {
if (!err) {
console.log("Data: " + JSON.stringify(data));
completed.push(data);
fcallback(null);
} else {
cb(err, null);
}
});
}
}, testme(completed));
My async functions are running correctly and each completing correctly but my testme(completed) runs immediately before any of my asynch functions ever finish. Not sure why..
my testme(completed) is simply:
function testme(completed) {
console.log("Completed: " + JSON.stringify(completed));
}
One note, my function to execution on each element itself has asynch functions inside of it (checkRDSTag(), processOrCreateLog(), etc). I'm guessing its something to do with the callback() that async is expecting / tracking executing out of place or something? Not really sure..
Retrun callback only when last item iterating
var index=0;
async.forEach(data.DBInstances, function (dbInstance, fcallback) {
let dbtype = dbInstance.Engine;
let logFilename = log[dbtype].log();
let instanceId = dbInstance.DBInstanceIdentifier;
if (tagFilter) {
let arn = dbInstance.DBInstanceArn;
checkRDSTag(arn, tagFilter, function (err, found) {
if (!err) {
//increament index here
index++;
//tag was found, continue processing and check other filters...
if (found) {
if (noFilter || (instanceTypes && instanceTypes.indexOf(dbtype))) {
//console.log('db type is: ' + dbtype);
processOrCreateLog(instanceId, dbType, function (err, data) {
if (!err) {
console.log("Data: " + JSON.stringify(data));
completed.push(data);
//check if last item running
if(index===data.DBInstances.length){
return fcallback(null);
}else{
fcallback()
}
} else {
cb(err, null);
}
});
}
} else {
//tag wasn't found but was specified, don't process anything...
console.log("tag specified was not found on instance: " + instanceId);
}
} else {
console.log("Error checking RDS Tag");
cb(err, null);
}
});
}
//only process filtered types...
else if (noFilter || (instanceTypes && instanceTypes.indexOf(dbtype))) {
console.log('db type is: ' + dbtype);
processOrCreateLog(instanceId, dbtype, fcallback, function (err, data, fcallback) {
if (!err) {
console.log("Data: " + JSON.stringify(data));
completed.push(data);
//check if last item running
if(index===data.DBInstances.length){
return fcallback(null);
}else{
fcallback()
}
} else {
cb(err, null);
}
});
}
}, testme(completed));
My problem ended up being in my other asynchronous call (processOrCreateLog()) within my iteratee. There was flow control logic in my asynchronous calls that didn't callback so fcallback() never ran.
Also to clarify, async is the async node.js library: https://caolan.github.io/async/docs.html#each
As long as you execute the callback on the iteratee for each element with either an error or null it can track all executions and will then run your final callback properly.
thank you for taking the time to read my question.
I have an array with records that I want to put into MYSQL database from NodeJS. These records have a jobkey field that I want to be UNIQUE, but I don't want it to be the PRIMARY KEY since the jobkey coming from an API and I want to use my own recid for better indexing and sorting.
I am using NodeJS to first check if the jobkey exists by doing a SELECT WHERE and checking if rows.length > 0? then adding the job if jobkey does not already exist. For some reason I keep getting a ER_DUP_ENTRY error and I can't figure out why my rows.length sometimes === 0 even though the jobkey exists. I have been hitting my head against the wall now for a few days. I hope it's not just a semi-colon or one of those simple errors I have overlooked. Anyways I need help please look at my code.
function is_job_key(_jobkey, cb){ // cb(err, flag)
var sql = 'SELECT * FROM tbl_indeed WHERE ?';
conn.query(sql, {jobkey: _jobkey}, function(err, rows){
if(err){
console.log(err);
return cb(true);
}
bar.tick();
if(rows.length > 0){ // jobkey exists
return cb(null, true);
}
cb(null, false);
});
}
function insert_job(posts, cb){ // cb(err)
var sql = 'INSERT INTO tbl_indeed SET ?';
conn.query(sql, posts, function(err, result){
if(err){
console.log(err);
return cb(true);
}
bar.tick();
cb(null);
});
}
function insert_all_jobs(job_arr, query_str, cb){ // cb(err, count_inserted)
function get_posts(job){
var posts = {jobkey: job.jobkey, snippet: job.snippet, url: job.url, jobtitle: job.jobtitle, company: job.company, date: job.date, query_string: query_str};
return posts;
}
bar = new progress(' ' + query_str + ' (:current / :total) [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
width: 40,
total: job_arr.length*2
});
var count_inserted = 0;
async.each(job_arr, function(job, cb){
var posts = get_posts(job);
is_job_key(job.jobkey, function(err, result){
if(err) return cb(true);
if(result){
bar.tick();
return cb(); // jobkey exists
}
insert_job(posts, function(err){
if(err) return cb(true);
count_inserted++;
cb();
});
});
}, function(err){
if(err) return cb(true);
console.log('done');
conn.end();
cb(null, count_inserted);
});
}
var job_arr = JSON.parse(fs.readFileSync('technician.txt', 'utf-8'));
//job_arr = job_arr.splice(1, 10); //for some reason this works ok...
insert_all_jobs(job_arr, 'technician', function(err, result){
if(err) return console.log('error');
console.log(result);
});
thank you for reading my question and have a lovely day
~A