promise is still pending in then block - how to resolve?

878 views Asked by At

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.

2

There are 2 answers

2
Nicholas Tower On BEST ANSWER

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;
  });
1
Supermacy On

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)
}