How to wait for a async function while running via shell in nodejs

Viewed 5485

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

1 Answers

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 ]
Related