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!
console.log('Done!')?await doIt(). Usingawait"inside" functions does not magically make the Promise "go away". It's still a Promise andawaitis just "sugar" to resolve it Just think of logically writingthen()in place of everyawaitand "then" ( yes "pun" ) it should be clear to you.