node.js - 如果在循环 node.js mongodb 中找到,则没有得到响应
问题描述
我find
在循环内使用 mongodb 查询,因为我需要运行find
查询 5 次。我为此使用了以下代码:
let result = {};
let miles = ['5','10','15','25'];
let i = 0;
while (i < miles.length) {
Shops.find({ 'shopInfo.address':{ $geoWithin:{ $centerSphere: [ [ 75.83183541365247, 30.902146005639267 ], miles[i] / 3959 ] } } }).then(response=>{
if(i==4){
result[miles[i]] = response.length;
res.json(result);
}else{
result[miles[i]] = response.length;
i++;
}
})
.catch(err=>{
console.log(err)
});
}
当我在浏览器上点击 api 时。它没有返回任何东西,并且在控制台中出现以下错误:
请帮助我,我该如何解决这个问题?
解决方案
会发生以下情况:
您的while
循环运行并启动异步操作。但是,由于该异步操作尚未完成i++
,因此不会执行,因此循环将永远运行,创建越来越多的异步操作来填满您的内存,最后 NodeJS 因为内存不足而崩溃。为防止这种情况,您不应使用异步任务同步迭代。循环内的await
异步任务或异步任务然后等待它们:.map
miles
const entries = Promise.all(miles.map(mile =>
Shops.find({ 'shopInfo.address':{ $geoWithin:{ $centerSphere: [ [ 75.83183541365247, 30.902146005639267 ], mile / 3959 ] } } })
.then(entry => ([mile, entry.length]))
));
entries.then(entries => {
const result = Object.fromEntries(entries);
//...
});
// Polyfill: Object.fromEntries
if(!Object.fromEntries)
Object.defineProperty(Object, "fromEntries", {
value(entries) {
const result = {};
for(const [k, v] of entries)
result[k] = v;
return result;
}
});
推荐阅读
- python - 仅使用 python 检查和处理平面文件,无需任何包或库
- javascript - webpack-cli@3.0.8 需要 webpack@^4.xx 的对等点,但没有安装
- hive - 查询从单独环境复制的 Hive 中的 ORC 数据
- c# - Microsoft Unity HierarchicalLifetimeManager 死锁
- c++ - 单例模式中的手动析构函数调用:多次调用
- jquery - 动态添加到表中的按钮不起作用 Jquery
- ruby-on-rails - 尝试在不中断 Rails 服务器的情况下运行 Python 脚本
- json - 在 Go 中编辑 Json 而不首先解组为结构
- node.js - 具有任何端口的 AWS localhost
- javascript - 当球与矩形碰撞时如何改变角度?