2

I am trying to get data from this API using fetch, and I know a promise pending is returned, but it isn't resolving itself so I can't use the data. I don't know what I am doing wrong.

function api () {
    return fetch('https://api.punkapi.com/v2/beers').then(respo => { respo.json() } ).then(data => { 
        const beersData = data;
        return beersData;
    }).catch(error => {
        console.error(error)
     }) ; 
}

api();

console.log(beersData)
JayDev95
  • 777
  • 2
  • 5
  • 18

1 Answers1

1

First of all, you need to remove curly bracket in first then. respo => respo.json() is equivalent to respo => { return respo.json() }.

And second, you need to handle promise when you call api function since api() also returns Promise.

function api () {
  return fetch('https://api.punkapi.com/v2/beers')
    .then(respo => respo.json())
    .then(data => { 
      const beersData = data;
      return beersData;
    }).catch(error => {
      console.error(error)
    }) ; 
}

api()
.then(res => {
  console.log(res);
})
Prime
  • 2,809
  • 1
  • 7
  • 23