Tomash
Tomash

Reputation: 21

Javascript / node.js - returning the value to parent function

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:

  1. make variable for the data, assing the data in the promise function and then return the variable
  2. 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

Answers (1)

suvroc
suvroc

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

Related Questions