Reputation: 21
as a node.js newbie, I'm having problems to understand how to return value of nested function. I'm trying to make a function that retrieve data from DB and returns it. Here is my code:
getRecent: function() {
var promise = models.download.find({}).sort({date_added: -1}).limit(5).exec();
promise.then(function(data) {
return data;
});
}
My goal is to get the function getRecent() return the data from mongo. My initial ideas were:
make something like this:
var test = promise.then(function(data) {
return data;
});
return test;
But since node.js code works asynchronously, it wouldn't work. I believe some synchronous libraries might help, but what's the proper and elegant way to do it?
Thank you,
Tom
Upvotes: 0
Views: 513
Reputation: 3062
You can just return promise and operate on this value out of the function
getRecent: function() {
return models.download.find({}).sort({date_added: -1}).limit(5).exec();
}
getRecent().then(function(data) {
// do something with data
});
Upvotes: 1