Estoy tratando de devolver la lista de direcciones describedIpList después de que se hayan resuelto todas las operaciones asincrónicas. Puedo ver algunas formas de resolver esto sin una promesa, pero estoy interesado en aprender cómo hacer esto en las mejores prácticas con una promesa, ¿realmente tengo que envolver otra promesa alrededor de mi función y si es así, muéstrame cómo hacerlo? haz esto correctamente.
const ipResolver = (ips) => { const describedIpList = []; ips.map((ip) => { Promise.all([ client.country(ip), client.city(ip) ]) .then(response => { [Country, City] = response; describedIpList.push({ ip, countryCode: Country.country.isoCode, postalCode: City.postal.code, cityName: City.city.names.en, timeZone: City.location.timeZone, accuracyRadius: City.location.accuracyRadius, }); console.log(describedIpList); }) .catch(err => describedIpList.push({ip, error: err.error})); return describedIpList; }); Reiterar. Estoy buscando devolver la lista de ips describedIpList después ips.map() y luego devolver una respuesta res.json({fullyDescribedIps: ipResolver(ips)});
Necesitará dos Promise.all s: uno para esperar a que se resuelvan todas las solicitudes de ip y otro para esperar a que se resuelva el país y la ciudad de todos ellos.
const ipResolver = ips => Promise.all( ips.map(ip => Promise.all([ client.country(ip), client.city(ip) ]) .then(([Country, City]) => ({ ip, countryCode: Country.country.isoCode, postalCode: City.postal.code, cityName: City.city.names.en, timeZone: City.location.timeZone, accuracyRadius: City.location.accuracyRadius, })) .catch(err => ({ ip, error: err.error })) ) );async function ipInfo(ip) { try { const [Country, City] = await Promise.all([ client.country(ip), client.city(ip), ]); // const [Country, City] = await client.countryAndCity(ip); return { ip, countryCode: Country.country.isoCode, postalCode: City.postal.code, cityName: City.city.names.en, timeZone: City.location.timeZone, accuracyRadius: City.location.accuracyRadius, } } catch (err) { return { ip, error: err.error }; } } const ipResolver = Promise.all(ips.map(ipInfo)); // const ipsInfo = await Promise.all(ips.map(ipInfo));