I am trying to get a web page to read text from files held on the same webserver. The following is the code I am using; it is cobbled together from several much-praised answers to similar questions on this site:
<html>
<head>
</head>
<body>
<h1>JavaScript Fetch API</h1>
<h2>The fetch() Method</h2>
<p>The first line of the file will go here</p>
<p id="sample">No file loaded</p>
<button id="startbutton">Click to try it</button>
<script>
document.getElementById("startbutton").addEventListener("click", starter);
function starter() {
alert("in js")
document.getElementById("sample").innerHTML = "Results: "
mytext = gettext("fetchsample.txt")
document.getElementById("sample").innerHTML += mytext
}
async function gettext(file) {
try {
gotfile = await fetch(file)
if (!gotfile.ok) document.getElementById("sample").innerHTML +=
"could not fetch" + file + " " + gotfile.statusText
};
}
catch (ferror) {
alert("fetch error " + ferror.message)
}
try {
myText = await gotfile.text();
if (!myText.ok) {
document.getElementById("sample").innerHTML +=
" could not read " + file + " ";
}
} catch (rerror) {
alert("read error " + rerror.message)
}
return myText
}
</script>
<body>
</html>
The file the code is trying to read, fetchsample.txt, is in the same directory on the server as the html code, so (I assume) there should be no CORS issues.
What happens is:
- the first alert (“in js”) fires correctly, so I know I am getting into the javascript.
- the second alert (“fetch error…”) does not fire, furthermore the “could not fetch…” string is not inserted into the paragraph “sample”, so I’m assuming the first await statement (involving fetch) completes successfully.
- however the second await statement does not complete successfully, because the if(!myText.ok) condition is activated: “could not read fetchsample.txt” is inserted into the paragraph “sample”. The catch statement is not taken, however.
- The routine gettext returns “[object Promise]” and this is inserted into the paragraph “sample”. Curiously, it appears before the “could not read…” message: the exact content of paragraph “sample” when this is run in Chrome or Firefox is “Results: [object Promise] could not read fetchsample.txt”, suggesting that gettext has returned that result before the second await statement has completed. I assume this is something to do with how async/await function in javascript.
Note that if you try to run the snippet from this site, it returns a network error, because the file reference is relative and the corresponding file doesn’t exist; but I can’t get out of that by putting in the full domain reference, presumably because of CORS.
So, what am I doing wrong here? Why is this code not returning the contents of fetchsample.txt?