-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.

6
  • 5
    res.json() is asynchronous as well. See the first example here: MDN: Using Fetch. Jan 22, 2019 at 15:10
  • That suggests thento resolve, but mine is pending even in then block. Jan 22, 2019 at 15:12
  • Have you read Tylers comment? you need to handle the promise in res.json() aswell
    – Liam
    Jan 22, 2019 at 15:13
  • 2
    @Prakhar fetch requires two thens. fetch() -> then -> result.json() -> then -> process result. Jan 22, 2019 at 15:14
  • Okay - I'm new to this world. I got it now. Jan 22, 2019 at 15:17

2 Answers 2

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;
  });
2
  • Does this works differtly with graphql-request - return request(this.GRAPHQL_ENDPOINT, query, variables) .then(res => { console.log('data is: ', res); return res; }) Jan 22, 2019 at 15:38
  • Apparently I'm getting pending with this now? Jan 22, 2019 at 15:39
-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)
}
1
  • How to resolve in debugger?
    – mathtick
    Dec 12, 2020 at 9:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.