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



从下面的代码中可以看到,我要创建一个对象数组,格式如下:

[{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})
});
});

你的问题中似乎缺少信息。如果你能张贴一个最小的可重复的例子会更好。

我认为你不太了解Promise.all是什么,你用它来包装一个数据数组,它不做任何事情。

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

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

这样的东西应该很接近。例如,一些细节可能不正确,这取决于您的服务调用实际返回的内容。此外,您可能希望处理错误情况!

// 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
});
});
});

相关内容

  • 没有找到相关文章

最新更新