首页 > 解决方案 > 如何在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)
            })   
    }

    });
})
}

})

标签: node.jsmongoose

解决方案


推荐阅读