Skip to content
Advertisement

I keep getting undefined after async call in another function

I Have 2 functions one which uses async and await to grab data and place it into an array. The second is acts like a checker to see if the user inputs a similar value as seen on the database

function repeatsChecker() {
  let api_data_values = []

  fetchData().then(data => {
    for (let i = 0; i < data.length; i++) {
      api_data_values.push(data[i].name)
    }
  })

  return api_data_values

}

// testing for similarities

async function test() {
  let name = "Joe"
  let test = await repeatsChecker();
  console.log(test[0])
}

test()

When I compile a simple if statement everything returns true and when I do console.log(test[0]) it returns undefined?

Advertisement

Answer

repeatChecker isn’t returning a promise, so the fact that you’re awaiting doesn’t have any meaningful effect. console.log(test[0]) executes before api_data_values.push(data[i].name).

Try this:

function repeatsChecker() {
  return fetchData().then(data => {
    return data.map(value => value.name);
  });
}

Or with async/await:

async function repeatsChecker() {
  const data = await fetchData();
  return data.map(value => value.name);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement