Understanding Fetch In Js
Solution 1:
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.
Solution 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.
Solution 3:
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() {
returnfetch('http://some-site.com/cors-enabled/some.json')
.then(function(response) {
returnJSON.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.
Post a Comment for "Understanding Fetch In Js"