从 Mongoose 中获取项目列表并返回结果

Fetching an list of items from Mongoose and returning the results

正如您从下面的代码中看到的,我正在尝试创建一个具有以下格式的对象数组:

[{Region: Africa, Countries: X, X, X}, {Region: Asia, Countries X, X, X}]

X 代替国家/地区名称。我能够成功创建这个对象数组。

创建完这个对象数组后,我想执行 res.send 200 来发送数据。问题是,在之前的所有配置中,我都会收到错误消息,因为 res.send 会尝试执行多次。现在我正尝试用承诺来做,并使用 Promise.all。我很确定我没有正确实现它,因为现在这段代码没有产生任何输出,而是没有输出。

这段代码非常接近它需要的地方...如果有人能告诉我我在这里缺少什么,那就太好了。它必须是有承诺的东西。

router.get("/FRPListing", async (req, res) => {
  //Array of all regions
  //Have a country list

  //Holder Array
  let regCountryList = new Array()

  //New Array
  let countryList = new Array()
  countryList.push("Europe and UK", "Africa", "Middle East and Gulf", "Eurasia", "Asia", "Australasia", "North America", "Central America Caribbean", "South America", "Global")

  countryList.forEach(async function (value) {
    let EuropeUK = await FRPObj.find({Region: value}, 'Region Country').sort({Country: 1}).distinct('Country').exec()
    let EuropeUKRegCountryList = new Object()
    EuropeUKRegCountryList.Region = value
    EuropeUKRegCountryList.Countries = EuropeUK
    regCountryList.push(EuropeUKRegCountryList)
  })

  Promise.all(regCountryList).then(values => {
    res.send({status: 200, results: regCountryList})
  });
});

您的问题中似乎缺少信息。如果能post一个minimal reproducible example.

就更好了

我认为你不太明白 Promise.all 是干什么用的,你用它来包装一个数据数组,它什么也没做。

相反,您应该构造一个承诺数组(对数据服务的调用)并将 that 传递给 Promise.allPromise.all 将调用传递给它的所有承诺,并等待它们全部解决。

在编写代码时,最好重命名一些变量,以便更清楚地说明意图。

像这样的事情应该很接近了。例如,某些细节可能不正确,具体取决于您的服务实际调用的内容 return。此外,您可能想要处理错误情况!

// You shouldn't need the `async` keyword decorating this function 
// if you're handling the callback using promises.  If you were using 
// "await" within the callback, for example, you would need it.
router.get("/FRPListing", (req, res) => {
  const regions = ["Europe and UK", "Africa", "Middle East and Gulf", "Eurasia", "Asia", "Australasia", "North America", "Central America Caribbean", "South America", "Global"];

  const fetchCountries = [];

  // First, build an array of promises (your async calls to your data source)
  for (const region of regions) {
    fetchCountries.push(
      FRPObj.find({
        Region: region
      }, 'Region Country').sort({
        Country: 1
      }).distinct('Country').exec();
    );
  }

  // Promise.all will return a results array with one entry per 
  // promise, and they will be in the order in which the original 
  // promises were pushed into the array.  Because the order is 
  // preserved, you can look up the region from the regions.
  Promise.all(fetchCountries).then(results => {
    const aggregatedResults = [];
    for (let i = 0; i < regions.length; i++) {
      const region = regions[i];
      const countries = results[i];
      aggregatedResults.push({
        Region: region,
        Countries: countries
      });
    }
    res.send({
      status: 200,
      results: aggregatedResults
    });
  });
});