-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
  • 25,247
  • 27
  • 110
  • 174
unknown_boundaries
  • 1,292
  • 1
  • 18
  • 44

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
  • 56,346
  • 6
  • 64
  • 75
-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,259
  • 12
  • 21