2

I checked out a few resources but don't really get the fetch method.

What is the point in having 2 then-s? What is the first and the second then good for? Why is a return in the first one?

fetch('http://some-site.com/cors-enabled/some.json')  
  .then(function(response) {  
    return response.text();  
  })  
  .then(function(text) {  
    console.log('Request successful', text);  
  })  
  .catch(function(error) {  
    log('Request failed', error)  
  });
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Sean Magyar
  • 2,360
  • 1
  • 25
  • 57
  • the return in the first `.then` is to get a promised value to the next `.then` - refer to [Promises](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) to understand this mechanism, as fetch uses Promises – Jaromanda X Jul 23 '16 at 09:18
  • MDN is a good source on Promises (or anything JS, really): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then … Simply put, you might want to do asynch / promise operations inside the `then` blocks, and to chain them one after the other. Returning a value from a `then` function carries it to the next `then` (if successful). – Aurel Bílý Jul 23 '16 at 09:21

3 Answers3

7

The then calls are based on so called Promises. See the Promises on Mozilla's documentation for a detailed description.

Chaining is a special use case of Promises. In your code snippet chaining is used for first extracting the text from the result of the external request response (return response.text();). The return value is then given as a parameter to the second then() which logs it onto the console.

This is especially useful if you want to do several separate, possibly asynchronous operations and want to have them separated and serialized. If any of these operations fail, the catch is called immediately like with an exception.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
  • Joachim, why do I need the chaining here? – Sean Magyar Jul 23 '16 at 09:49
  • I suppose your example doesn't really *need* chaining, it only illustrates that the result of each `then` (again a promise) can be used just the same. Chaining is very useful if you want to "serialize" asynchronous actions. Without them you would have to nest callback functions. – JSchirrmacher Jul 23 '16 at 09:55
  • The example illustrates further that the result of the first `then` is the argument of the second. – JSchirrmacher Jul 23 '16 at 09:56
2

For a much detailed answer please follow the documentation links fetch and promises

The 'fetch' function, perform an asynchronous operation, and always return a Promise object.

My purpose, here, is just to clarify something you seems to had not catched and help you to understand better the documentation.

The '.then' are Promise's object method, that call some code when the asynchronous operation is done.

'.then' are call sequentially if the Promise is considered 'resolved', otherwise the '.catch' is call to handle the error.

The return statement in the function passed to '.then' is the imput of the second queued '.then'.

In the example you post, there are 2 queued '.then' just to show it is possible to do it and how to do.

There is no need to use more than one '.then', it is just useful as you could split up the action performed in retrieving data in different steps so you could abort the promise, if you got an error.

This helps to write clean code and debugging, ad you could generalize some actions and reuse, and alzò have more défaillance errors.

Mario Santini
  • 2,905
  • 2
  • 20
  • 27
  • Mario, waht I don't understand is that why do I need the second `then`? Why do I have to chain? I mean the way I see there is a promse if the AJAX call succeeds then I'm using the `then` if fails then I'm using the `catch`. So just don't see the advantage of chaining here. – Sean Magyar Jul 23 '16 at 09:47
1

Each then returns a promise and the result of each subsequent then is passed to the latter.

Lets say you have employeeservice

class EmployeeService {

getEmployees() {
       return fetch('http://some-site.com/cors-enabled/some.json')  
           .then(function(response) {  
           return JSON.parse(response.text());  
       })  

      .catch(function(error) {  
      log('Request failed', error)  
     });
}

}

fetch url returns some response but that is not in json , service can actually modify the response and then pass the result to the main component

employeeService.getEmployees().then(function(json) {  
           console.log('Request sucJcessful', text);  
})  

Consider first then as a modifier.

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • Piyush, why do I need the second `then` that you call modifier? – Sean Magyar Jul 23 '16 at 09:48
  • you can omit the first then , process your results in employeeService.getEmployees().then , but its a general convention that your service should give you the parsed usable things – Piyush.kapoor Jul 23 '16 at 09:53