0

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

1 Answer 1

1

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.