0

I have a text.txt file and I want to save its content in a variable. My problem is that I can log the text but I can't store it in a var

let fileText;
fetch("./text.txt")
    .then(response => response.text())
    .then(text => fileText = text);
    console.log(fileText);  // undefined
Amin Sanei
  • 39
  • 6

1 Answers1

2

The console.log will be executed before the fetch promise resolved.

If you want line-by-line syntax execution you can use async/await.

let fileText;

(async () => {
const response = await fetch("./text.txt")
const text = await response.text()
fileText = text;
console.log(fileText);
})()
Mina
  • 14,386
  • 3
  • 13
  • 26