Reputation: 717
I am trying to create a repository class/ function in javascript but because of the callbacks I am unable to return a value from the function:
this.getAll = function(collection)
{
var result;
collection.find(function (err, objects) {
if (err) return console.error(err);
console.log(objects);
var result = objects;
});
return result;
}
var result = repo.getAll(Kitten);
console.log(result);
but the result here is called first and the callback called later. Is it a good idea to do what I'm trying to do? Or should I just pass in a callback function into the repository?
Upvotes: 0
Views: 3578
Reputation: 1466
You should learn how to use callbacks. If you don't like the syntax it creates, you can use promises instead. Callbacks in JavaScript and NodeJS is fundamental. But to avoid the christmas tree effect, refactor you code into functions and methods. I whould also recommend you take a look at the async module, specifically async.series and async.parallel.
You can take a look at the following blog that highlights some valid points about nodejs.
Upvotes: 0
Reputation: 1044
I use callbacks. It think it is NodeJS feature. Also you can use promises instead of callbacks.
You can create method for repository like as:
function getAll(collection, cb){
collection.find(function (err, objects) {
cb(err, objects);
});
}
getAll(Kitten, function(err, objects){
console.log(objects);
});
Upvotes: 2