I have three functions
async function inventories() {
print("starting inventories")
sleepFor(5000)
// Here I am querying a mongodb database
const inventoriesRes = await db.inventories.find({})
return inventoriesRes
}
async function costs() {
print("starting costs")
const costsRes = await db.costs.find({})
return costsRes
}
async function users() {
print("starting users")
const users = await db.users.find({})
return usersRes
}
I want :
- The queries to be all executed in //
- Once all are finished, print the results
Here's my solution
const dbqueries = async () => {
const [result1, result2, result3] = await Promise.all([inventories(), costs(), users()])
return {result1, result2, result3}
}
dbqueries.then(results => {
print(JSON.stringify(results))
}).catch(error => {
throw error
});
The problem is that I am not this solution works as I want. To verify, I've put a sleep (see code below) in the inventories()
function.
What's happening is
printing starting inventories
waiting for 5 seconds
printing costs
printing users
This let me think that costs() didn't start in parallel. If it had started earlier, I would have
printing starting inventories
printing costs
printing users
...
function sleepFor(sleepDuration){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){
/* Do nothing */
}
}
Either my solution is wrong, or the sleepFor
function is doing something more than just putting to sleep only the inventories()
function. Any help?
PS. print
works exactly like console.log()
in mongoshell which is a fully-functional JS interpreter