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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With