Javascript fetch
function asynchronously pulls a resource from the specified url
. Meanwhile fetch
returns a Promise
. Promise
helps with the asynchronous part and runs the function passed into then
(res => res.json()
) once the resource is loaded with the fetched resource as parameter. The fetched resource can be parsed using json()
if it is JSON formatted.
then
also returns a Promise
making it chainable.
fetch(url) // asynchronously load contents of the url
// return a Promise that resolves when res is loaded
.then(res => res.json()) // call this function when res is loaded
// return a Promise with result of above function
.then(res => { // call this function when the above chained Promise resolves
this.setState({
data: res,
error: res.error || null,
loading: false
});
res => res.json()
can also be written as (but not exactly equal)
function(res) { return res.json()}