0

I am new to asynchronous JavaScript and I have been learning how to fetch data from 3rd party APIs. While on it, I came across a small issue:

const users = fetch('https://jsonplaceholder.typicode.com/users')
  .then((res) => { // <--- with curly braces
      res.json()
  })
  .then((data) => {
    console.log(data)
  })
const users = fetch('https://jsonplaceholder.typicode.com/users')
  .then((res) => res.json()) // <--- without curly braces
  .then((data) => {
    console.log(data)
  })

With the curly braces, I got the result as undefined.

Whereas without the curly braces, I get the entire data.

How and why is this possible? Has anybody come across this situation before?

Edric
  • 24,639
  • 13
  • 81
  • 91
Abishek H
  • 210
  • 1
  • 10

1 Answers1

2

Hay Abishek;

These are two different notations for arrow functions:

  1. An arrow function with expression body, in which case that expression implicitly / automatically is the returned value
(a, b) => expression
  1. An arrow function with a block statement as body. This is similar to "normal" function expressions and declarations, the curly braces denote the block. You have to explicitly return a value.
(a, b) => {
  statement;
  statement;
  return expression;
}
Kelley van Evert
  • 1,063
  • 2
  • 9
  • 17