0

I wrote this async function that fetches data from an API.

const getData = async () => {
  const response = await fetch(`${url}`);
  const json = await response.json();
  return json.results.slice(0,3);
}

I expect it to return an array containing 3 objects.

I call the getData function in a non-async function

function App() {
  const thing = getData().then(data => data);
  console.log("Thing is: " + thing);
}

But instead of my array being printed out I'm getting "Thing is: [object Promise]" and I don't know why. I've read around and it says that async functions will always return a promise, so although my return statement in getData defines an array of 3 objects it will ultimately return a promise that is once resolved I can access that array. So I go ahead and then use .then when I call the getData function, but still I'm getting the promise instead of the data? I think I'm doing something wrong with the arrow function, I don't know if I'm returning the data correctly.

Dupocas
  • 20,285
  • 6
  • 38
  • 56
aDabOfRanch
  • 137
  • 9
  • `getData().then(console.log)` – dandavis Aug 21 '19 at 16:18
  • @dandavis Yes I noticed that will give me the data but I want to ultimately store the array in a variable. So what would I do instead? – aDabOfRanch Aug 21 '19 at 16:19
  • 1
    `var array; function App(){ getData().then(x=>array=x)}` gets it outside the callback. your challenge is then more _when_ to access that var than _where_ to access it. – dandavis Aug 21 '19 at 16:20
  • @dandavis I did `const thing = getData().then(data => {return data});` and then `console.log(thing)` but the array still doesn't get printed. – aDabOfRanch Aug 21 '19 at 16:25
  • The return value of a `then` function is always a Promise. You can't escape the fact that asynchronous code means that the value won't exist until the future. You have to use a mechanism (like `await` or `then`) to wait until the value is available. – Quentin Aug 21 '19 at 16:25

0 Answers0