Reputation: 11247
Async and callbacks are still concepts I struggle with. I have been reading and trying to make sense of code that uses them to gain more familiarity. I don't understand why this snippet of code uses a callback instead of just passing in a value (instead of an anonymous function with the argument as the value to be evaluated).
Shorten.prototype.Lookup = function (url, callback){
var mongoose = this.app.locals.settings.mongoose;
var Cursor = mongoose.model('urls');
Cursor.find({"linkFinal": url}, function(err, docs){
if (err === null){
if (typeof(callback) === "function"){
if (docs[0] !== undefined){
callback(docs[0]);
return docs[0];
}else{
callback(false);
return false;
}
}
}else{
console.log(err);
}
});
};
This is the code function in a use case:
shorten.LookUp(url, function(urlCheck){
if (urlCheck === false){
//Add to db
// another function that uses a callback as second parameter
shorten.addLink(shortenURL, shortURL){
small.shortenedURL = "http://" + domain + "/" + shortURL.link;
small.shortenError = false;
small.alreadyShortened = false;
res.json(small);
});
}else{
small.shortenedURL = "http://" + domain + "/" + urlCheck.link;
small.shortenError = false;
small.alreadyShortened = true;
res.json(small);
}
});
My only intuition for reason on why to use a callback function in this scenario is that when the query is made to the Database (in this case mongodb using Mongoose api) the function is only run when the data is available(which is the case with:
// after the result of the query is ran, the result is passed to the function in
// the docs parameter.
Cursor.find({"linkFinal": url}, function(err, docs){
This is the main reason I can come up with on why a callback is passed instead of just a value. I am still not 100% certain on why this wouldn't work:
Shorten.prototype.LLookUp = function (url, value){
var mongoose = this.app.locals.settings.mongoose;
var Cursor = mongoose.model('urls');
Cursor.find({"linkFinal": url}, function(err, docs){
if (err === null){
if (docs[0] !== undefined){
return docs[0];
}else{
value = false;
return false;
}
}
}else{
console.log(err);
}
});
};
All I did in this scenario was remove the the anonymous function and passed the argument of that function instead.
Thanks!
Upvotes: 0
Views: 85
Reputation: 140210
The return
statements are inside the callback function, not the LLookUp
function. So they will return to whoever calls the callback (mongoose library), however mongoose library doesn't do anything with the value the callback returns so it's useless to return any value.
Upvotes: 1