0

I am using js fetch request. I have this inside a function, when I call the function I want it to return my data.
This is not happening.
It would appear that the promise is not getting 'resolved'.

I clearly don't fully understand promises, so any advice on that in relation to the below example would be very useful.

Here is my sample code:

const test = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos')
  const data = await response.json()
  return data;
}

console.log(test())

Output:

// [object promise]
{}

Question: How can I write the fetch request so that when I run test(), it returns me the json as I would expect?

Thank you

Jonny
  • 1,053
  • 1
  • 13
  • 26
  • You need to await `test()` or use `.then` to get the value – evolutionxbox May 12 '22 at 09:14
  • @evolutionxbox - thanks, await test how? _ I am already awaiting data, which should be returned no? – Jonny May 12 '22 at 09:16
  • Instead of `cosnole.log(test())` write `test().then(console.log)` – Shikhar Awasthi May 12 '22 at 09:21
  • @Shikhar - Thank you, I see I can log the results, but what if I wanted to use the results? I mean to say - In another function, I simply want to get those results. Which is why I like to call the function and simply have it return those results. Is this possible or am I misunderstanding? – Jonny May 12 '22 at 09:24
  • You can use the results like this, `test().then((response)=>/*do something here*/ console.log(response))` – Shikhar Awasthi May 12 '22 at 09:30
  • @Shikhar I just want to save the results, they will be called by another function at a later point. – Jonny May 12 '22 at 09:35
  • So for that you can declare on global variable and save the response in that variable in then function. Something like: `let response = []; test().then((res)=>response = Array.from(res))` – Shikhar Awasthi May 12 '22 at 09:41

0 Answers0