I am getting
Uncaught SyntaxError: Unexpected end of JSON input
error in the console when I try to parse JSON data above the if statement within the eventListner scope, but it also outputs the expected data.
const getData = (link, callback) => {
const request = new XMLHttpRequest();
request.open('GET', link);
request.send();
const err = `couldn't fetch data Error COde:${request.status}`;
request.addEventListener('readystatechange', () => {
const data = JSON.parse(request.responseText);
if (request.readyState === 4 && request.status === 200) {
callback(data, undefined)
}
else if (request.readyState === 4)
callback(undefined, err);
});
}
const link = '/tom.json'
getData(link, (err, data) => {
if (err) console.log(err);
else
console.log(data);
});
output:
VM133780:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at XMLHttpRequest. (async.js:13:27)
(anonymous) @ async.js:13
XMLHttpRequest.send (async)
getData @ async.js:9
(anonymous) @ async.js:28
async.js:29 (3) [{…}, {…}, {…}]
if I place the JSON.parse(); within the if statement, it doesn't show any error and outputs the data as expected `
const getData = (link, callback) => {
const request = new XMLHttpRequest();
request.open('GET', link);
request.send();
request.addEventListener('readystatechange', () => {
const err = `couldn't fetch data ErrorCOde:${request.status}`;
if (request.readyState === 4 && request.status === 200) {
const data = JSON.parse(request.responseText);
callback(data, undefined)
}
else if (request.readyState === 4)
callback(undefined, err);
});
}
const link = '/tom.json'
getData(link, (err, data) => {
if (err) console.log(err);
else
console.log(data);
});
output
async.js:30
(3) [{…}, {…}, {…}]
what's the difference?