I'm running a ubuntu server on vagarnt on windows. I have a JSON file on document root in a folder. I want to use async/await to fetch that JSON data. Here is the code I came up with after Googling and learning.
async function getJSON() {
try {
var result = await makeRequest("GET", "./form-data/test-items/test.json");
console.log(result);
} catch(error) {
console.log(error);
}
}
function makeRequest(method, url) {
return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/json");
xhr.addEventListener("readystatechange", function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var respond = xhr.responseText;
resolve(respond);
} else {
reject(xhr.statusText);
}
}, false);
xhr.open(method, url, true);
xhr.send();
});
}
document.addEventListener("DOMContentLoaded", getJSON, false);
The problem is that only the catch block in the async function has been running. I'm sure I get the respond text from the Ajax request since I have tested it on console. But I don't know how the await statement has been failing.
How can I fix this? And which part have I been missing?