-2

Hello my problem is about function inside '.then' function. Why my standart function isn't working ? But when arrow function works. What is main difference between arrow function and standart function

fetch('cart/',{
    method:'post',
    headers:{'Content-Type':'application/json'},
    body : JSON.stringify({'something':'something' })
 }) 

.then( res=> res.json())
        .then(data => console.log(data));

Above code works .Also this is my approach

fetch('cart/',{
    method:'post',
    headers:{'Content-Type':'application/json'},
    body : JSON.stringify({slug: g})
    })

.then( function (res){ res.json() )
        .then(function (res) { console.log(res) });
  • Did you miss an assignment on the first line? – mjwills Jul 31 '21 at 09:21
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"**Describe the problem. "It doesn't work" isn't descriptive enough** to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it. Use a brief but descriptive summary of your problem as the title of your question."_ – Andreas Jul 31 '21 at 09:23
  • Option 1 logs `data`. Option 2 does "nothing". What do you expect to happen? – Andreas Jul 31 '21 at 09:25
  • @Andreas now I edited my real code and i found that the problem is that i didn't write 'return ' before 'res.json() ' .So when I use arrow function does it automatically return variable and i don't need to write return? – Nihat Abdullazade Jul 31 '21 at 09:32
  • In your first version of the question there was `return res;`... Please spent more time with proofreading _before_ you post your question. – Andreas Jul 31 '21 at 09:33
  • Duplicate of: [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – Andreas Jul 31 '21 at 09:35

2 Answers2

0

You are not returning res.json() in the standard function so there won't be anything going in the "then" block thats why it wont log

kavandalal
  • 114
  • 6
0

It does not work because you need to return value:

.then(function (res) { return res.json() })

See this.

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

Nathan Xabedi
  • 1,097
  • 1
  • 11
  • 18