【问题标题】:how to can get the value of callback function out side callback function in express js如何在express js中获取回调函数的值
【发布时间】:2020-09-22 10:01:36
【问题描述】:
app.get('/allColleges', (req, res) => {

 collegeModel.find().sort({ field: 'asc', _id: -1 }).exec((err, colleges) => {
        if (!colleges || colleges.length === 0) {
          return res.status(200).json(null)
        } else {
          var collegedata = Array.from(colleges)
 
          for (i = 0; i < collegedata.length; i++) {
            var collegeGalleryData = {};
            var collegeGallery = collegeGalleryModel.find({collegeId: collegedata[i]._id}, (err, collegeGallery) => {
                if (!collegeGallery || collegeGallery.length > 0){
                    collegeGalleryData.data = collegeGallery;
                } 
            })
            collegedata[i].collegeGallery = collegeGalleryData.data;
          }
            
         }

  return res.json(collegedata)
 })

})

我在 Express JS 中创建了一个 API。在这个 API 中,我需要查询结果传递到的回调函数之外的集合中的数据。 我创建了一个对象变量并在回调函数中添加了一个键“数据”,并尝试将其值设置为使用collegeGalleryModel 在第二个查询中找到的数据。 当我在回调函数outside这个对象中检查data 的值时,它是空的。 那么,我们怎样才能得到传递给回调函数外部回调函数的结果值呢?

【问题讨论】:

  • 你在用猫鼬吗?
  • 尝试在查询中使用 async/await api 而不是回调

标签: node.js mongodb express callback


【解决方案1】:

问题是您无法在这种情况下将值传递给它之外的回调函数,因为 closures 在 javascript 中的工作方式。

我不确定我是否正确理解了您的问题,但似乎对于collegedata 数组中的每个对象,您都希望运行一些查询并将结果存储在对象中的collegeGallery 键中。

您可以轻松地为此使用async-await

我是这样重构的:

app.get('/allColleges', (req, res) => {

  (async() => {

    try{
       const colleges = await collegeModel.find().sort({ field: 'asc', _id: -1 }).exec();
              let collegedata = null;
              
                if(colleges.length>0){
                  collegedata = Array.from(colleges);
       
                  for (const dataObj of collegedata) {

                      const collegeGallery = await collegeGalleryModel.find({collegeId: dataObj._id})
                      dataObj.collegeGallery = collegeGallery;
                   }

                }

        res.json(collegedata);

    } catch(e) {
      console.error(`ERROR: ${e.message}`);

      res.status(500).send({
        message: e.message || "INTERNAL SERVER ERROR"
      })
    }
     

  })();

})

不过,对您的代码的一些观察:

  1. 您似乎没有进行错误处理,我为您做了一些;您可以根据自己的要求进行修改。
  2. 根据您的代码,如果第一个查询没有返回任何对象,您将使用null 进行响应。我在任何地方都没有看到,我不确定快递会允许你这样做。但是,我重构的代码也会以 null 响应,尽管我更愿意返回空数组或 404 响应。

【讨论】:

  • 如果对您有用,请将其标记为正确答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-13
  • 2013-03-15
  • 2020-12-16
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多