Home > Enterprise >  How to resolve an asynchronous function when returning a hoisted array?
How to resolve an asynchronous function when returning a hoisted array?

Time:03-09

I'm trying to return describedIpList after all async operations are resolved. I can see a few ways to solve this without a promise, but I am interested in learning how to do this in best practice with a promise, do I really have to wrap another promise around my function and if so, please show me how to do this correctly.

 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;

    });

To reiterate. I am looking to return describedIpList after ips.map() resolves and then return a response res.json({fullyDescribedIps: ipResolver(ips)});

CodePudding user response:

You'll need two Promise.alls - one to wait for all ip requests to resolve, and one to wait for the country and city of all of those to resolve.

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

CodePudding user response:

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));
  • Related