-2

Can I return the value of an object from a function?

I have a service layer that has the business logic, and I am trying to call a repository layer to retrieve data from MongoDB.

The problem is:

 ClienteGet(req) {
        var response;

        repo.get(req.params.clienteId, (err, response) => {
            console.log(response); -> here I have the correct data
        });

        console.log(response); -> only shows undefined
        return response;
    };

This is my repository method:

get(clienteId, res) {
       mongoose.model('Cliente').findById(clienteId, res);
   };

ClienteGet needs to return the response to the controller, to be shown on the FrontEnd.

I can I acess the response outside of the function scope?

EDIT:

Repository method

    get(clienteId, res) {
        mongoose.model('Cliente').findById(clienteId, res);
    };
DiogoMartins
  • 77
  • 1
  • 7

1 Answers1

-1

Use this code:

 ClienteGet async (req) {
        let response;

        await repo.get(req.params.clienteId, (err, res) => {
            response = res;
        });

        return response;
    };
jkdev
  • 11,360
  • 15
  • 54
  • 77
alex067
  • 3,159
  • 1
  • 11
  • 17