3

I have a simple code in node.js

async function dbQuery() {
        const MongoClient = require('mongodb').MongoClient; 
        const url = "mongodb://localhost:27017/"; 
        const db = await MongoClient.connect(url);
        const dbo = db.db("mydb");
        const result = await dbo.collection("tblData").find({}).toArray()
        return result;
    }

async function doIt() {
        try {
              const res = await dbQuery();
              console.log("Records: " + res.length);
            } catch (error) {
              console.log(error);
            }
   }
//
console.log("Starting...")
doIt()
console.log("Done!")

the output is:

Starting...
Done!
Records: 24

how to force the code to wait for the query to finish? to have the output like:

Starting...
Records: 24
Done!
3
  • 2
    It's because 'doIt()' is async. What exactly do u need? Commented Jun 5, 2018 at 4:08
  • As per your code, the execution is right. But if you want to perform some other actions then you need to write code in that way. this is not your complete code better to provide the case why you want to wait for just console.log('Done!')? Commented Jun 5, 2018 at 4:20
  • 1
    await doIt(). Using await "inside" functions does not magically make the Promise "go away". It's still a Promise and await is just "sugar" to resolve it Just think of logically writing then() in place of every await and "then" ( yes "pun" ) it should be clear to you. Commented Jun 5, 2018 at 4:24

3 Answers 3

3

The other answer says use Promises, but I don't think that would be necessary, you are using async and await, a more up to date implementation of Promises.

Just move the doIt() function call into an async call. Since this is node, and is non blocking, this would be a more correct implementation.

async function dbQuery() {
    const MongoClient = require('mongodb').MongoClient; 
    const url = "mongodb://localhost:27017/"; 
    const db = await MongoClient.connect(url);
    const dbo = db.db("mydb");
    const result = await dbo.collection("tblData").find({}).toArray()
    return result;
}

async function doIt() {
    console.log("Starting...");
    try {
        const res = await dbQuery();
        console.log("Records: " + res.length);
    } catch (error) {
        console.log(error);
    }
    console.log("Done!");
}

doIt();
Sign up to request clarification or add additional context in comments.

Comments

0

You could always use promises to do the job.

async function doIt() {
  return new Promise((resolve, reject) => {
    try {
          const res = await dbQuery();
          console.log("Records: " + res.length);
          resolve();
        } catch (error) {
          reject(error);
        }
  });
}

console.log("Starting...")
doIt().then(() => {
   console.log("Done!");
})
.catch(err => console.log(err))

Comments

0

you just need to call your doIt() function by await and its working..

something...
await doit();
something...

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.