-1

Code below retrieves the JSON data without any problems.

     app.get('/startgame', (req, res) => {
     res.send('Welcome To The Start Of The Game')
     fetch("https://deckofcardsapi.com/api/deck/new/shuffle/deck_count=1")
     .then(res => res.json())
     .then(json => console.log(json)) 
    })

Code below returns undefined when I do console.log(json). The only difference between these two blocks of code are the squiggly brackets on the bottom block of code. I would like to know why exactly is this happening. My understanding is that they should both produce the same result.

   app.get('/startgame', (req, res) => {
     res.send('Welcome To The Start Of The Game')
     fetch("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1")
    .then((res) => {res.json()})
    .then((json) => {console.log(json)})

})

1 Answers1

1

The reason is that this syntax:

() => foo()

Is short for:

() => { return foo(); }

On this line in your code:

.then((res) => { res.json() })

you are no longer returning the result of res.json(). You need to explicitly use return when you use curly braces:

.then((res) => { return res.json(); })

Which is equivalent to:

.then((res) => res.json())
Evert
  • 93,428
  • 18
  • 118
  • 189