0

I have a directory on my webserver where I upload timestamp.md files for publishing to my "blog"-div on my site. Using javascript to fetch index of dir via scandir() (PHP) returns:

["2018-12-05T13:28:10.000Z.md","2018-12-05T12:58:19.858Z.md","2018-12-05T12:37:25.012Z.md","2018-12-05T12:28:52.612Z.md","..","."]

I store obve in var "files".

I then do a for-loop with fetch from index.html to get content of all off the timestamp.mds

(I create a emtpy array for storing of md-content)

var mdcontent = new Array()

for(var i=0;i<files.length -2;i++) {

    fetch('md/'+files[i])
    .then( response => response.text())
    .then(result => mdcontent.push(result));

}

console.log(mdcontent) returns what looks like a normal array 
consol.log(mdcontent[0]) (or any other element of array) returns undefined.
console.log(mdcontent.lenght) returns 0.

The question is how to access elements of this array?

I cant figure out where I went wrong this time and if someone could help me I would appreciate it!

Thanks in advance

Farooq Ahmed Khan
  • 3,975
  • 3
  • 27
  • 36
antsve
  • 1
  • 1

1 Answers1

2

When you use fetch it returns Promise, which represents an asynchronous operation. You should not access elements of mdcontent like you do - it's OK with synchronous code, but not here. Instead you need to wait while every promise (every fetch + .text()) will be completed. You can do it with Promise.all.

var promises = new Array();

for (var i=0; i < files.length - 2; i++) {
    promises.push(
        fetch('md/' + files[i])
        .then(res => res.text())
    );
}

Promise.all(promises).then(mdcontent => {
    console.log(mdcontent);
    console.log(mdcontent.length);
    console.log(mdcontent[0]);
});

I suggest you to read about asynchronous javascript. Maybe this article. It could be hard to use promises, when you don't understand its asynchronous nature. You also may want to use asynchronous functions and await instead of .then(...).

qwermike
  • 1,446
  • 2
  • 12
  • 24
  • thanks for the input! You were indeed right. Went the async/wait way to solve my issue though. this was my final code: `const request = async () => { const response = await fetch('md/'+files[i]) const text = await response.text() var mdcontent = marked(text.toString()) console.log(mdcontent)` } – antsve Dec 06 '18 at 13:40