Promises/Fetch in JavaScript: how to extract text from text file
Fetch doesn't return a promise for the text of a response - it returns a promise for a Response
object available after headers have been received.
This is so you can do cool things like:
- Determine how you want to read the body of the response based on the headers.
- Stream the response progressively etc.
If you want the text of the response - you can .text()
the Response
objects to get a promise for that:
Promise.all([
fetch('sample.txt').then(x => x.text()),
fetch('sample2.txt').then(x => x.text())
]).then(([sampleResp, sample2Resp]) => {
console.log(sampleResp);
console.log(sample2Resp);
});
Use async/await
async function getSampleText() {
console.log( (await fetch('sample.txt')).text() );
console.log( (await fetch('sample2.txt')).text() );
}