nodejs/pg, callback parameters - javascript

I am fairly new to node.js, and haven't done much of javascripts. Tried to search my problem, but couldn't find specific answer related to it.
So, while I was working on attaching the PostgreSQL to my app, I followed a snippet from some example on web, and it seems like working pretty well.
Anyways I wanted to understand how it works, I had a problem understanding specific part of the following code:
module.exports = {
query: function(text, values, cb) {
pool.connect(function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
console.log(client);
client.query(text, values, function(err, result) {
done();
cb(err, result);
})
});
}
}
and the specific part is:
pool.connect(function(err, client, done) { ... }
What I understood is connect function takes callback function with err, client, and done as parameter, however I couldn't understand from where the function(err, client, done) is passed to connect function as parameter. By where, I mean an object or a caller that call connect function.
I had suspected that it would be handled internally, but I wanted to know clearly.

Bydefault all callback function, the first parameter must be an error and second will be a result of ur callback function.
Done is similar to callback keyword, which says, your task is over and give response back from where the function has called, its just like return statement in normal function
example:
function callbackDemo(arg1, arg2, callback) {
if (condition)
callback(null, "Success");
else
callback("error");
}
callbackDemo(1, 2, function(err, result){
if(!err)
console(result);
else
console.log(err);
});

Related

Callback is not a function in nodejs

I am trying to implement classMethods of a sequelize model for authentication.
authenticate: function(password, callback) { // authenticate a given login body
bcrypt.compare(password, this.password_hash, function (err, isMatch) {
if (err) return callback(err);
callback(null, isMatch);
});
},
When I try to run the above codes, the command said "callback is not a function".
How are you calling authenticate? Make sure when you write your callback as a parameter you don't use parentheses. So make sure you do 'authenticate(foo,bar)' instead of authenticate(foo,bar())'

What is "done" callback function in Passport Strategy Configure "use" function

I'm an node.js and express.js noob. This question may seems silly but I'm really in confusion.
I'm trying to configure Local Strategry authentication by using passport. As shown in the official documentation, we can figure this Local Strategy by the following code,
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
My confusion is about the done callback function. When the official docs show this local strategy using as a middleware in the route handler, there is no need to pass the function parameter for this done callback.
app.post('/login',
passport.authenticate('local'),
function(req, res) {
res.redirect('/');
});
So, isn't this done callback function will be null if we don't provide the function parameter? If not, what is that done callback function and what processes will be happening in this done callback function?
done is a method called internally by the strategy implementation.
Then it navigates you, as you can see, to one of the success / error / fail methods (again, by the implementation. there are more options).
Each of these options may calls to the next, where in your snippet code is the following:
function(req, res) {
res.redirect('/');
});
When success is called, it can attach the user to the request or do other things, depending on your needs (it looks for the options you pass to passport.authenticate). If you want to determine when next will be called, you should use custom callback which gives you more flexibility.
I strongly recommend that you read the source.
It's now 2022 and I had the same question. The passport documentation has improved and it describes the done method (also called cb) here: https://www.passportjs.org/concepts/authentication/strategies/#verify-function. You will need to call this yourself in your strategy's verify function.
A verify function yields under one of three conditions: success, failure, or an error.
If the verify function finds a user to which the credential belongs, and that credential is valid, it calls the callback with the authenticating user:
return cb(null, user);
If the credential does not belong to a known user, or is not valid, the verify function calls the callback with false to indicate an authentication failure:
return cb(null, false);
If an error occurs, such as the database not being available, the callback is called with an error, in idiomatic Node.js style:
return cb(err);

How do I call MySql procedures from Node JS

I want to call a stored procedure from MySql node:
How do I call it? The documentation says:
You can call stored procedures from your queries as with any other mysql driver. If the stored procedure produces several result sets, they are exposed to you the same way as the results for multiple statement queries
I tried searching for it on internet but got very old results which do not work anymore.
I tried:
connection.query('procedure_name()', {84,Bhuwan}, function(err, result) {
connection.destroy();
if (err)
throw err;
callback(err, result);
});
But I am getting error.
Can anyone provide a proper syntax for it??
You have to use 'call' command and if you have parameters to pass to the query, you need to add '?' marks. Check the code.
connection.query("call procedure_name(?,?)", [param1, param2], function (err, result) {
if (err) {
console.log("err:", err);
} else {
console.log("results:", result);
}
});

Nested callbacks in javascript

I have a small problem with nested callbacks in javascript. Apparently im doing something wrong, but i did my research and tried to follow the tutorials avaialble throughout the web. I know that my code works, since query returns proper data, but i have no idea why my code doesnt "wait" within executeQuery method till the res is fetched from database, it just goes straight to "oh noes" section.
DatabaseConnection.prototype.executeQuery = function(query, executeQueryDone){
var activeConnection;
console.log("YEAAA, executing Query: " + query);
this.pool.getConnection(function (err, connection){
console.log("Got Connection, we are ready to go!");
if (err){
console.log("Error, DAMMNIT! " + err);
executeQueryDone(err);
}
activeConnection = connection;
activeConnection.connect();
activeConnection.query(query, function(error, res){
console.log("Connection from pool is executing Query");
if(error){
console.log("Error during executing query");
executeQueryDone(error);
}
else {
console.log(" OK now release connection (dont be selfish)! ");
activeConnection.release();
executeQueryDone(null, res);
}
});
});
console.log("oh noes! IM AFTER CONNECTION, why dude? WHY???? ");
};
I'd be grateful for any hints since im struggling with that since yesterday.
=====================
PROBLEM SOLVED:
generally all was OK, the "issue" was mistakenly written test:
i made it like that:
describe('testDB2', function () {
it('should return proper STUFF', function (done) {
assert.equal(1, someService.getStuff(function(err, result){
if (err === null){
console.log("err is null, as it should be!");
}
console.log(" result from DB " + result[1].NUMBERS);
}));
});
});
while is should be like that:
describe('testDB2', function () {
it('should return proper STUFF', function (done) {
someService.getStuff(function(err, result){
assert.equal(err, null);
assert.equal(result[1].NUMBERS, 43637654);
done();
});
});
});
as a result (in the incorrect case), i didnt fetch the result the way i wanted as assert couldnt "catch up"
thanks to all for the enlightment ;)
Your console.log call isn't part of a callback, so it will be called as soon as the getConnection call is made. If you want it to be called only after your callback to getConnection fires, you either need to call it at the end of that call, or you need to use some form of promises.
Javascript is single threaded, but it does use a task queue. When the database connection is instantiated and the pool connected to, the response to that is placed into the task queue to be executed or actioned when complete.
Directly after placing that in the task queue the next piece of execution is the log that does the "oh noes" - nice messaging btw lol.
So essentially what happens is the db call gets placed in the task queue for later execution, and then the log occurs, and then the task queue executes at a later time with the db response.

Node.js Express and Mongoose, rendering after a save()

I just started experimenting with Node.js Express and Mongoose by creating a simple blog website.
I am trying to build some routes that will do some simple db operations, but I'm getting confused with asynchronous functions and if my code will execute properly every time.
This is basically what I have:
app.get('/createUser', function(req, resp) {
var newUser = new User({name: 'abc123', pass: 'password321'});
newUser.save(function(err){ // will this callback always be called correctly?
if(err) resp.send('ERROR!');
resp.send('SUCCESS!');
});
});
So I want the response to be written out as "ERROR!" for any error in saving, and "SUCCESS!" when the save was successful. However, I'm confused about the timing of these functions. Will the get() function ever return before the save() is completed? And if so, will the response not be written out properly?
The get() function will complete before the save function does, but since there is nothing writing a response until the save callback is executed then the response won't be available to the browser until then.
I added a few console.log() calls to your code so you can see the order of execution:
app.get('/createUser', function(req, resp) {
console.log('this will print first');
var newUser = new User({name: 'abc123', pass: 'password321'});
newUser.save(function(err){ // will this callback always be called correctly?
console.log('this will print last');
if(err) {
resp.send('ERROR!');
}
else {
resp.send('SUCCESS!');
}
});
console.log('this will print second');
});

Categories

Resources