2

I have a file

demo.js

with a function that waits for fetch data from DB like this

exports.findNames = async () => {
  const names= await Student.find();
  console.log('Names:', names);
  return names;
};

So, while I testing this function via the shell/command line, which not waiting for the function to be completed.

Tested like this

node ./demo findNames

NB: Student is a model, response sending from another file that's why not here. and it's not a middleware. Mongoose used as db tool

2
  • what is your demo js code? Commented Jun 27, 2019 at 18:02
  • its a simple nodejs file for getting students details from db using mongoose. Commented Jun 27, 2019 at 18:10

1 Answer 1

1

You need to await or .then the function in your demo.js. Let me give you an example:

names.js

exports.findNames = async () => {
    const names= await new Promise((res,rej)=>{
        setTimeout(()=>{
            res([1,2,3])
        }, 100);
    });
    console.log('Names:', names);
};

demo.js

const name = require('./names');
(async ()=>{
    await name.findNames();
})();

Output

$ node demo.js
Names: [ 1, 2, 3 ]
Sign up to request clarification or add additional context in comments.

4 Comments

There is a problem with your demo.js code. Please post it here, because this example works.
Updated code with relevant info. res sending from another file that's why not here. and it's not a middleware.
You need to have a driver function like my demo.js to call your findNames function
It never returns.

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.