简体   繁体   中英

Why I'm getting a <pending> Promise?

const fsPromises = require("fs").promises;
const path = require("path");

const getCities = async (country) => {
  const cities = [];

  try {
    const data = await fsPromises.readFile(
      path.join(__dirname, "countries-and-cities.csv"),
      "utf8"
    );
    const records = data.split("\n");
    for (const record of records) {
      if (record.toLocaleLowerCase().includes(country.toLowerCase())) {
        cities.push(record.split(",")[1]);
      }
    }

    return cities;
  } catch (error) {
    console.log(error);
  }
};

const result = getCities("United States");
console.log(result);

I'm trying to read a csv file and then get the cities of a given country in an array. I don't know what I'm doing wrong, if I console.log inside the loop the data is there.

Because the promise is still pending

You wanted to wait for it like that:

getCities("United States").then(result => console.log(result));

You need to await for your async function:

const result = await getCities("United States");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM