i am new in javascript/node js. So a little thing about function in js makes me confused. Here i have problem.
I have a function in a file (appModel.js) called getUserById
to return a row from database by id
as a parameter.
User.getUserById = function getUserById(id,result){
var koneksi = new newDb();
koneksi.query('Select ID, email, name, status, telp_no, company_id, created_at, updated_at from user where ID = ?',id)
.then(rows=>{
console.log("user: ",rows);
result(null,rows);
})
.catch(err=>{
console.log('error: ',err);
koneksi.close().then(()=>result(err,null));
});
};
module.exports = User;
and i access appModel file through different file from (appRoute.js) using
var User = require('../models/appModel');
I've tried to access getUserById function in appRoute.js by
var _a;
var _check = User.getUserById(req.params.id, function(err,user){
if(err){
_a = err;
}else{
_a = user;
}
return _a;
});
console.log('res', _check);
when i print _check
itself the result is res undefined
so, i expect the output from this function is an error
or user
itself. How can i get that?
Your problem isn't actually modules related.
Its actually a lack of understanding of asynchronous processes and closures in general.
If you add a console.log in there as follows, you'll find that your 'res' runs before 'done'.
var _a;
var _check = User.getUserById(req.params.id, function(err,user){
console.log('done', err, user); // <-- Add this in here.
if(err){
_a = err;
}else{
_a = user;
}
return _a;
});
console.log('res', _check);
The second part about closures, the return value in here is ignored:
_check = User.getUserById(req.params.id, function(err,user){
...
return _a; // This is ignored. It will never be assigned to _check.
}
The return value actually comes from:
function getUserById(id,result){
var koneksi = new newDb();
...
return "test"; // Here. Add this last line and try again.
};
You're not returning anything from getUserById
, so until an explicit return is added to a function in JavaScript, the result from calling it will always be undefined
.
Your result
function is simply a callback. While it is indeed returning a value, that value isn't further being used in getUserById
or being passed on to anything else, mainly because you're not returning anything from your then
/ catch
blocks.
Suggested reading on Promises: https://developers.google.com/web/fundamentals/primers/promises
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.