0

The following code successfully retrieves the json from this API url, however if I try to access, say the status I can't return it at the same time as the retrieved data.

I would love to understand fetch a bit better. You can see my attempt as a comment.

const url = 'https://randomuser.me/api/?results=10';

fetch(url)
.then((resp) => {


    status = resp.status;
    responsejson = resp.json();
    console.log( responsejson );

    return responsejson;
    //return {"status":status, "responsejson":responsejson} ;

})
.then(function(data) {
    console.log( data );
})
.catch(function(error) {
console.log(error);
});
Calvin
  • 194
  • 17
  • `resp.json()` returns a promise, so you either return it and chain another `.then()`, or `await` it. – Terry Mar 16 '21 at 20:02

2 Answers2

0

Personally, I use async/await rather than .then. Here is an example:

<script type='module'>
  let response = await fetch('https://randomuser.me/api/?results=10');
  let json = await response.json();
  //If you wanted to count the number of males vs females:
  let numberMales = json.results.map(i=>i.gender).filter(a=>a=='male').length;
  let numberFemales = json.results.map(i=>i.gender).filter(a=>a=='female').length;
  console.log(`There are ${numberFemales} females and ${numberMales} males.`)
</script>
quicVO
  • 778
  • 4
  • 13
  • Also, note that rather than doing ``, you can also wrap it in an `async` function or use `.then` to unwrap the promises. – quicVO Mar 16 '21 at 20:15
0

That's because resp.json() is an async method so you have to wait until the promise is complete to access the responsejson info.

So, when you return resp.json() you're returning a promise that can be handled with a then statement and when you return {"status":status, "responsejson":responsejson} you're not returning a promise but an object with a promise inside.

The then statement only catches the return responsejson becuase is a promise.

Juan Rambal
  • 573
  • 2
  • 6