0

I try to fetch a text from a local txt file and create an array consisted of all words from the file. Just like ['this', 'is', 'a', 'sample', 'text'...]. The problem is that I cannot do anything with the resulting array. I cannot loop it with forEach or even access any item. I think I should transform the array is some way but have no idea how. This is the screenshot of the array in console Probably the question is quite silly, but I am very beginner at JS. Thanks.

const arr = []
fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
console.log(arr)
Serg988
  • 1
  • 1
  • `response.text` or `response.json` here `.then(response => response.text())`? – brk May 12 '20 at 09:06
  • how do you try to use the array and what failure are you getting? – Always Learning May 12 '20 at 09:14
  • Thank you. But the idea was to save the rsulted array and use it outside. I am searching for the solution since yesterday and still have not found anything. – Serg988 May 12 '20 at 09:31
  • to use outside of the `fetch` you can use aysnc/await as described in my answer below, but it has a ripple effect that the function you're using it in will now return a Promise – Always Learning May 12 '20 at 09:48
  • Thanks! It took me another few hours of reading/watching tutorials but now I understand how it works. – Serg988 May 12 '20 at 14:54

1 Answers1

1

Note that fetch is asynchronous so everything in the then functions will not get done before your final console.log(arr) call. If you want to do something with the data in the array, then it should be done within the Promise chain like this:

const arr = []
fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
    .then(() => {
        console.log(arr)
        arr.forEach(word => console.log(word))
    })
// outside here the array is still empty

If you want to use it outside then you can use async/await like this:

async function myFunction {
const arr = []
await fetch('sample.txt')
    .then(response => response.text())
    .then(data => data.split(' '))
    .then(result => arr.push(...result))
arr.forEach(word => console.log(word))
}

This causes processing of your function to wait until the fetch call (and all subsequent then statements) to complete before continuing. By doing this you guarantee that arr has been populated. Note though, that you must declare your function as async which means it now returns a Promise object and needs to be treated as asynchronous.

Always Learning
  • 5,510
  • 2
  • 17
  • 34