How to stop rest of code from executing NodeJs? - javascript

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();
}

Related

node.js else if statement issue, close but no cigar

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);
}
});
});
}

Node.js - Getting data from mother query to a nested query

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!");
})
}

Async write after select Pouchdb

I'm trying to check if an element exist before inserting it in my bdd.
I have to do this in order to (in the future) modify this existing element.
I'm using PouchDb and PouchDb-find with Node 6.9.1.
Actually I'm doing this:
for(var i = 0; i < 10;i++ ){
(function(_count, _pdb){
var count = _count;
var db = _pdb;
db.find({
selector: {numeroCandidat: parseInt(results[count].no_apb)}
}).then((result) => {
if(result.docs.length != 0){
console.log("l'étudiant existe");
}else{
console.log("l'étudiant n'existe pas");
var etudiant = {
"numeroCandidat": results[count].no_apb,
"nom": results[count].nom,
"numeroGroupe": "gr" + results[count].groupe,
"filiere": results[count].libelle,
};
db.post(etudiant).then((response) =>{
// handle response
console.log("STUDENT CREATED");
}).catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
});
})(i, this.pdb);
};
But the problem is : Due to the asynchronous version of my select query... if an element exists two times it appends that the second select occurred BEFORE the insertion of the first element, and I have this element two times in my database. I don't know how to deal with this one.
SO.. I'v found a workaround !
Simply create a function that I call recursivly after writting into my database.
Goodbye for loop.
var createStudents = function(_count, _pdb, _students){
if(_count >= 10) return;
console.log(_count);
var count = _count;
var db = _pdb;
var students = _students.slice(0);
db.find({
selector: {numeroCandidat: parseInt(students[count].no_apb)}
}).then((result) => {
if(result.docs.length != 0){
console.log("l'étudiant existe");
createStudents(++count,db,results);
}else{
var etudiant = {
"numeroCandidat": students[count].no_apb,
"nom": students[count].nom,
"numeroGroupe": "gr" + students[count].groupe,
"filiere": students[count].libelle,
"etudiantComms": [
{"commentaire": students[count].commentaire}
]
};
db.post(etudiant).then((response) =>{
// handle response
console.log("STUDENT CREATED");
createStudents(++count,db,results);
}).catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
});
}
createStudents(0,this.pdb,results);

NodeJS for loops with Mongo / HTTP call firing late

I'm fairly new to NodeJS and am still trying to wrap my head around the async nature of it, as well as when things are fired.
I've labeled each of the loops in the order that I expect them to fire with console.log() messages below. There are 4 loops in total that I expect to iterate in order.
When I hit the 'test call' end point, I begin by iterating through a list of data.
exports.testCall = function (req, res) {
var list = myData;
// Iterate through each list item and update MongoDB
for (var i=0; i<list.length; i++) {
var country = list[i].country;
var codeGroups = list[i].codes;
console.log('Loop #1');
for (var j=0; j<codeGroups.length; j++) {
console.log('Loop #2');
queryAndUpdateCodeGroup(codeGroups[j], country);
}
}
}
For each of the above 'codeGroups', I want to run a process that makes a call to my HTTP client, retrieves the data for that code group, and then update my MongoDB with that data.
function queryAndUpdateCodeGroup(group, country) {
myHTTPClient.itemLookup({
browseGroup: group,
country: country
}).then(function success (results) {
console.log('Loop #3');
for (var i=0; i<results.length; i++) {
var childrenArray = results[i].childArray;
var subCatArray = [];
var id = results[i].currentID;
var icon = '';
var name = getNameByCode(country, results[i].currentID);
for (var j=0; j<childrenArray.length; j++) {
subCatArray.push({name: childrenArray[j].name, itemID: id, icon: ''})
}
checkItem(name, id, icon, subCatArray);
}
}).catch(function error (err) {
console.log('ERR: ', JSON.stringify(err));
return err;
handleError(res, err);
});
}
Once the HTTP request is successful, I run this checkItem function which will either create a new entry in Mongo or will update an existing entry. Once this is complete, I want to start the process over for the remaining results in "loop #3". When Loop #3 has completed, I want to return to Loop #2 and repeat until this has completed for loop #2. When loop #2 has completed, I want to repeat this process in loop #1.
function checkItem(name, id, icon, subcats) {
console.log('Loop #4');
MyCategories.findOne({itemID: id}, function (err, cat) {
if (cat === null) {
console.log('ADDING NEW ITEM: ', name);
var newItem = new MyCategories({
name: name,
itemID: id,
icon: icon,
subCats: subcats
});
newItem.save(function (err) {
if (err) {
handleError(err);
return;
}
})
.then(function (res) {
console.log('New Item Success: ', newCatSuccess);
});
} else {
//Update item with latest info
var conditions = { itemID: currNodeId };
var update = { $set: { subCats: subcats }};
MyCategories.update(conditions, update, function (err, updated) {
if (err) {
handleError(err);
} else {
console.log('ITEM HAS BEEN UPDATED SUCCESSFULLY.');
}
});
}
});
}
Loop #1, and loop #2 seem to fire back and forth until completion, but loop #3 fires after #1 and #2 have completed, and #4 doesn't fire at all. How can I 'wait' until each step has completed before I continue on?

node.js return data from find collection in loop

I am trying to return data from this function. Console.log(documents) successfully shows the data in console. But this works only in body of the function. I can't return this data to the template. What should I do? Should I use some async package for node.js, or can be accomplished somehow like this?
Thank you.
var projects = req.user.projects;
var docs = [];
db.collection('documents', function(err, collection) {
for (i = 0; i < projects.length; i++) {
collection.find({'_projectDn': projects[i].dn},function(err, cursor) {
cursor.each(function(err, documents) {
if(documents != null){
console.log(documents);
//or docs += documents;
}
});
});
}
});
console.log(documents); // undefined
res.render('projects.handlebars', {
user : req.user,
documents: docs
});
Those db functions are async, which means that when you try to log it, the function hasn't finished yet. You can log it using a callback, for example:
function getDocuments(callback) {
db.collection('documents', function(err, collection) {
for (i = 0; i < projects.length; i++) {
collection.find({
'_projectDn': projects[i].dn
}, function(err, cursor) {
cursor.each(function(err, documents) {
if (documents !== null) {
console.log(documents);
callback(documents);// run the function given in the callback argument
}
});
});
}
});
}
//use the function passing another function as argument
getDocuments(function(documents) {
console.log('Documents: ' + documents);
});

Categories