I am trying to write a validation function, that validates my request headers. It returns true if all headers are ok and false if there is something wrong. I execute this function for every (almost) request. The problem is, I don't know how to return the main function in case I use callbacks and setting any flags does not work, due to some issues with variable scope. Everything was good when I was working without callbacks, I just used underscore to query my JSONs. Now I use NeDB and bound to callbacks I cannot get the job done. I tried to use a global "res" variable but the problem is, when I assign the value of parameter "cnt" (0 if token not found, 1 if there is a token) to "res", then the value of "res" is always 1 iteration behind "cnt": i.e.:
request1 (valid): cnt = 1; res = undefined;
request2 (valid): cnt = 1; res = 1;
request3 (invalid): cnt = 0; res = 1;
request4 (valid): cnt = 1; res = 0;
All I want to do is to return the main function with true if "cnt" = 1 and false if "cnt" = 0, either with help of a global variable or using another method.
function validateHeaders(request) {
if (request.headers.username && request.headers.deviceid) {
if (...) {
function getResult(callback) {
db.tokens.count({...
}, function (err, cnt) {
if (err) {
console.log(err);
} else {
callback(cnt);
}
});
}
getResult(function (cnt) {
res = cnt;
console.log({
count: cnt
});
});
console.log({
result: res
});
} else {
return false;
}
} else {
return false;
}
}