Koa 不等待 MongoDB 响应并返回 null 响应
我正在为客户创建一个应用程序。我在应用程序中使用 koa.js mongodb(用于数据库)。我试图获取客户详细信息以及特定客户的总提醒,但 koa 不会等待承诺并在我尝试致电时返回“[]”作为响应该路线
是我的代码
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;
})
})
,这是我调用此路线时的响应图像:
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:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试 Promise.all 而不是 new Promise
Try Promise.all instead new Promise
你那里有很多额外的东西。
这背后的想法是什么?
如果这部分
remind_col.find({}).toArray()
返回一个数组,为什么要放入数组中然后获取第一个元素?我坚信,您可以简单地在下面使用它,
因为它不是中间件,您不需要向上下文对象分配任何内容。
您定义了承诺,但从未解决价值。
我清理了一下你的代码,我认为这对你有用
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