This might have been discussed here a thousand times but I'm still unable to get this to work properly. Feel free to mark it as duplicate, I'm asking it nonetheless. Here's what I want:
- Fetch a JSON file from the web server
- Extract and return the JSON file content as JavaScript object
- Handle all errors that might occur in the above steps
All those steps should be done with the latest EcmaScript version that is feasible to be used in 2021 in a single function. Here's what I have:
async function getFile() {
try {
const response = await fetch("js/importantFile.json");
if(response.ok) {
return await response.json();
} else {
throw new Error(response.statusText);
}
} catch(error) {
console.log("Failed to fetch JSON file: ", error);
}
return "";
}
Executing the code ends up with a promise object in state pending
if I call the function as follows:
let jsonContent = getFile();
Besides this, am I missing something that needs to be done in terms of error handling?