Como puede ver en el siguiente código, lo que intento hacer es crear una matriz de objetos con el siguiente formato:
[{Region: Africa, Countries: X, X, X}, {Region: Asia, Countries X, X, X}]Las X están en lugar de los nombres de los países. Puedo crear esta matriz de objetos con éxito.
Cuando termine de crear esta matriz de objetos, quiero hacer un res.send 200 para enviar los datos. El problema es que, en todas las configuraciones anteriores, obtendría un error porque res.send intentaría ejecutarse varias veces. Ahora estoy intentando hacerlo con promesas y usando Promise.all . Estoy bastante seguro de que lo he implementado incorrectamente porque ahora, en lugar de producir algo, este código no produce ningún resultado.
Este código está tan cerca de donde debe estar... si alguien pudiera mostrarme lo que me estoy perdiendo aquí, sería genial. Tiene que ser algo con las promesas.
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}) }); });Parece que falta información en su pregunta. Sería mejor si pudiera publicar un ejemplo mínimo reproducible .
Creo que no comprende muy bien para qué Promise.all , y lo está usando para envolver una matriz de datos, que no hace nada.
En su lugar, debe construir una matriz de promesas (las llamadas a sus servicios de datos) y pasar eso a Promise.all . Promise.all invocará todas las promesas que se le pasaron y esperará a que se resuelvan todas.
Mientras trabaja en el código, sería bueno cambiar el nombre de algunas de las variables para aclarar un poco la intención.
Algo así debería estar cerca. Es posible que algunos de los detalles no sean correctos, dependiendo de lo que realmente devuelvan sus llamadas de servicio, por ejemplo. Además, es posible que desee manejar casos de error.
// 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 }); }); });