-2

The problem is that I want to use the array elsewhere in my code. But I do not know how to access it? Is there any other way to read the file and turn it into an array that I can use?

var dir = 'file.txt';

function file() {
const fileUrl = dir;

fetch(fileUrl)
    .then( response => response.text() )
    .then( text => readFile(text) )
}

function readFile(text) {
var lines = text.split('\n');
var array = [];
var str;

for (var i = 0; i < lines.length; i++) {
    var str = lines[i];
    tmp = str.split(",");
    array[i] = tmp;
}

}

file.txt

W,W,W,W,W,W,W,W,W
B,B,B,B,B,B,B,B,B
C,C,C,C,C,C,C,C,C
D,D,D,D,D,D,D,D,D

neonithe
  • 1
  • 1
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – MauriceNino Oct 05 '20 at 13:20

1 Answers1

0

To use that you would need to return the array from the function so you will need to do something like this.

var dir = 'file.txt';
var result; // Just to store the output

function file() {
    const fileUrl = dir;

    fetch(fileUrl)
        .then(response => response.text())
        .then(text => {
            result = readFile(text)
        })
}

function readFile(text) {
    var lines = text.split('\n');
    var array = [];
    var str;

    for (var i = 0; i < lines.length; i++) {
        var str = lines[i];
        tmp = str.split(",");
        array[i] = tmp;
    }
     

    return array;
}

Notice the variable result on the second line.

Frank Dax
  • 108
  • 7
  • I have tried this before I posted the question. And same as the last time I get "Undefined" back when I try to run it in the console. – neonithe Oct 07 '20 at 21:33