Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js + mongodb: wait for query to complete

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!
like image 897
sad nomad Avatar asked May 25 '26 16:05

sad nomad


1 Answers

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();