如何在express js中获取回调函数之外的回调函数的值

how to can get the value of callback function out side callback function in express js

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 的第二个查询中找到的数据。 当我在回调函数外部这个对象中检查data的值时,它是空的。 那么,我们如何在回调函数之外获取传递给回调函数的结果值呢?

问题是在这种情况下你不能获得传递给它之外的回调函数的值,因为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. 根据您的代码,如果第一个查询 return 没有对象,您将使用 null 进行响应。我在任何地方都没有看到过,我不确定 express 是否允许你这样做。然而,我的重构代码也将以 null 响应,尽管我更喜欢 return 空数组或 404 响应。