I’m creating a application for client. and I’m using koa.js mongodb(for database) in application.I’m trying to get customers details with total reminders with specific customers but koa is not waiting for promise and returning "[]" in response whenever i try to call that route
here’s my code
router.get("/getcustomers",async (ctx)=>{
ctx.customers = [await remind_col.find({}).toArray()][0];
ctx.customeralgo = [];
new Promise((reso,reje)=>{
ctx.customers.map(async cust=>{
return {
email:cust.email,
first_name:cust.first_name,
last_name:cust.last_name,
//------------- This is the when I'm trying to get count for customer
total_reminders:[await remind_col.count({"email":cust.email})][0],
//----------------
}
})
}).then(rlt=>{
ctx.customeralgo = rlt;
console.log(rlt);
ctx.body = ctx.customeralgo;
})
})
and this is response image when I call this route:
2
Answers
Try Promise.all instead new Promise
You have a bunch of extra things there.
What is the idea behind this?
If this part
remind_col.find({}).toArray()
returns an array why you are putting inside array and then getting the first element?I strongly believe, you can simply use this below
Since it is not a middleware you don’t need to assign anything to the context object.
You defined promise but never resolve a value.
I clean your code a bit and I assume this would work for you