Working Solution
Combining then
with catch
works.
fetch('http://some-site.com/api/some.json')
.then(function(response) { // first then()
if(response.ok)
{
return response.text();
}
throw new Error('Something went wrong.');
})
.then(function(text) { // second then()
console.log('Request successful', text);
})
.catch(function(error) { // catch
console.log('Request failed', error);
});
Details
fetch()
returns a Promise
containing a Response
object. The Promise
can become either fulfilled or rejected. Fulfillment runs the first then()
, returns its promise, and runs the second then()
. Rejection throws on the first then()
and jumps to the catch()
.
References
MDN - Promise
MDN - Checking that the fetch was successful
Google - Introduction to Fetch