0

I'm trying to return a query retrieving it from a mongo database in Node.js.
`

function find(){
    var result="";
    dbc.find(obj).toArray().then((res)=>{
        result=res;
      },(err)=>{
        throw err;
      }
    );
    return result;

}`

When I try to return the result and log it, undefined is what I get. I even tried to declare the result globally yet it didn't work. So I tried to use the bottom code and it worked.

`

function find(){
 var result="";
 dbc.find(obj).toArray().then((res)=>{
 fs.writeFileSync('new.txt',JSON.stringify(res));
 },(err)=>{
 throw err;
 }
 );
 result=JSON.parse(fs.readFileSync('new.txt'));
 return result;
}

`

I'm very new to Node.js, is there any better way to do this?

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Mar 04 '18 at 10:10

1 Answers1

0
function find(){
    return dbc.find(obj).toArray();
}
find()
   .then(res => console.log(res))
   .catch(err=> console.log(err));