// GitHub users
document.getElementById('btn3').addEventListener('click', fetchData);
// Fetching from external API
function fetchData() {
fetch('https://api.github.com/users')
.then(function (res) {
console.log(res.ok); //true
return res.json();
})
.then(handleErrors)
.then(function (users) {
let output = '';
users.forEach(user => output += `<li>${user.login}</li>`);
document.getElementById('output').innerHTML = output;
})
.catch(function (err) {
console.log(err);
});
}
// Handling fetch HTTP errors
function handleErrors(res) {
if (!res.ok) throw new Error(res.error);
return res;
}
Output in developer console:
true
app.js:55 Error
at handleErrors (app.js:61)
If I modify my handleErrors
function to this:
function handleErrors(res) {
if (!!res.ok) throw new Error(res.error);
return res;
}
Then it works as expected
Questions:
- What's the issue with my implementation of the
handleErrors
function?- What does the
!!
operator do?- Where can I find good resources to learn asynchronous programming, specifically AJAX?