node.js - 如何在for循环内返回对象
问题描述
我想返回 for 循环内的“项目”以及两个附加函数。“项目”是一个对象(我不会说变量),它由三个数组元素组成,并且可以更多取决于情况。所以我需要返回“项目”,这样我就可以在外面访问它,我可以使用 res.send() 将它发送给客户端。如果我在循环和函数内发送数据,它会返回一个名为“错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头”的错误。我找到了解决方法,但在实施它们时,什么都没有发生。它给我带来了同样的错误。我正在考虑做它回调函数,但我对如何在这种情况下使用它感到困惑。提前致谢。
router.get("/send" , async (req, res) => {
try {
res.send("hello")
//await sendData()
getCollectionNames()
} catch (error) {
console.log(error);
}
function getCollectionNames(){
MongoClient.connect(url, function(err, db) {
var db = db.db('admin')
mongoose.connection.db.listCollections().toArray(function (err, names) {
for(let index = 0; index < names.length; index ++){
if (err) {
console.log(err);
}
let name = names[index].name
const collection = db.collection(name)
collection.find().toArray(function(err, items){
console.log(items)
})
}
});
})
}
})
解决方案
推荐阅读
- database - Neo4j 适合 BI 用途吗?
- python - 如何从 csv 文件中自动获取标题
- javascript - ReferenceError:全局未在 xml2js 中定义
- python-3.x - Python3字符串到数字
- kubernetes - StatefulSet 重新创建 pod,为什么?
- django - AWS CodePipeline - 部署到 Elastic Beanstalk 需要 18 小时。我如何取消它?
- javascript - 如何在 Express 中将价值从一条路线传递到另一条路线?
- android - 如何在 Android 的图层列表中调整位图图像的大小?
- java - Spring ResponseBody 的 ObjectMapper 和 Jackson 的 ObjectMapper 的区别?
- javascript - 使用 jquery 引导表单验证