Reputation: 1074
I'm wondering how (if possible) I can create the same function, with exactly the same functionality, but to be used with a callback or without it. Here is an example with the "wanted effect" that is not working:
function getUsers(req, res, onComplete) {
// If the user is not logged in send an error. In other case, send data
if (!req.session.session_id) {
if (typeof onComplete === 'function') {
onComplete({error: true, msg: 'You are not logged in'});
} else {
res.json({error: true, msg: 'You are not logged in'});
}
} else {
//Another similar code...
}
}
It's not working because if I call "getUsers(req, res)", the typeof onComplete is always function, so I cannot detect when I call with or without the callback.
The exact problem is that I can call this function from inside my code, with callback (a normal call, like getUsers(req, res, function(cb) {//Do something with cb});
OR I can call this function from an AJAX call in my website, like http://localhost:8080/api/getUsers
, what in that case is when it don't works.
In the last case I get typeof onComplete === 'function'
as true, so I never get the else part executed. I'm supposing that the "request" done by the http call have more parameters than req&res, and that's the reason why onComplete is a function, instead of undefined.
The usual AJAX call is like this (javascript in the client side):
function getAllUsers() {
$.ajax({
url: '/api/getUsers',
type: 'GET',
success: function(data) {
// Remove item and set as main topic the assigned on the server
printUsers(data.users[0]);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
And the route defined in the config.json of my Node.JS to call the final function is like that:
{"path": "/api/getUsers", "method":"get", "callback": "api#getUsers"},
Upvotes: 0
Views: 77
Reputation: 1217
If you call getUsers without onComplete the value will be set to undefined. You can then check that case in your function.
function getUsers(req, res, onComplete) {
// Set onComplete to default call back if it is undefined
onComplete = onComplete || function(msg){ res.json(msg) };
if (!req.session.session_id) {
onComplete({error: true, msg: 'You are not logged in'});
} else {
//Another similar code...
}
}
See http://www.markhansen.co.nz/javascript-optional-parameters/ for more ways of doing this
Upvotes: 3