0

I am new to using Javascript, and I have read that using the fetch API is a nice way to get the text from a local '.txt' file. I've tried using the fetch calling it asynchronously and not, but haven't had any luck in changing my results.

`let quotes = [];
async function getQuotes() {
    const response = await fetch('../resources/music-quotes.txt');
    const longText = await response.text();
    return longText
}
getQuotes().then(data => quotes = [...data.split('|')]);

quotes.forEach(quote => console.log(quote))
const numberOfQuotes = quotes.length;`

When I go into the console window on chrome, there is no quotes being logged from the second to last line. But when I enter 'quotes' in the console, it returns the array of quotes. Furthermore, when I send in numberOfQuotes, it returns 0, but if I assign a new variable to quotes.length in the console, it returns the correct length.This scenario is the picture attached

This makes me think that it is not initializing the 'quotes' variable before I am calling it, but I thought changing the getQuotes() function to be asynchronous would solve that problem by making it await. What am I missing here? Thank you for the help in advance

  • There is nothing that would cause the bottom two lines of code to _wait_ for the previous lines to finish. `.then(data => quotes = [...data.split('|')])` is _useless_, because after this Promise chain successfully ends, there is _nothing_ that _actually uses_ `quotes`. Try using your browser’s [debug capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a). See [What is a debugger and how can it help me diagnose problems?](/q/25385173/4642212). Learn what order asynchronous code is executed in. – Sebastian Simon Feb 02 '23 at 04:28

0 Answers0