-1

I have code something like -

fetch(`${URL}${PATH}`)
   .then(res => {
       const d = res.json();
       console.log("data is: ", d);

       return d;
    })

It logs data is: Promise { <pending> }.

What to do to see results and utilize in next code statement?

Other questions and answers suggests to use then block to resolve, but I'm still seeing it unresolved.

Liam
  • 27,717
  • 28
  • 128
  • 190
unknown_boundaries
  • 1,482
  • 3
  • 25
  • 47

2 Answers2

3

res.json() is asynchronous. You will need to use an additional .then to get the result.

fetch(`${URL}${PATH}`)
  .then(res => res.json())
  .then(d => {
    console.log('data is: ', d);
    return d;
  });
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
-1

Well If you are getting this type of value Promise { <pending> }. Always remember to resolve it.
So your query would resolve to

fetch(`${URL}${PATH}`)
   .then(res => res.json())
   .then(console.log)
   .catch(console.error)

For better understanding you can leverage the use of async/await feature. The above code would reduce to-

try{
   const res = await fetch(`${URL}${PATH}`)
   const dataAsJson = await res.json()
   console.log(data)
}
catch(ex) {
   console.error(ex)
}
Supermacy
  • 1,429
  • 15
  • 24