0

I am collecting the content of a server side directory an store this in an array. After returning the array to the calling function array.length reports zero and the elements are not accessible as array[]. The representation of the array using console.log looks OK however.

function loadDir(targetDir) {
            var itemCount = 0;
            const directory = targetDir;
            const selector =
                ".icon-js, .icon-directory"; // selector for the relevant links in the directory's index page
            const request = new XMLHttpRequest();
            request.open("GET", directory, true);
            var dirListA = [];            
            request.onload = () => {
                // succesful response                
                if (request.status >= 200 && request.status < 400) {
                    const doc = new DOMParser().parseFromString(request.responseText,
                        "text/html"); // create DOM from response HTML                    
                    const links = doc.querySelectorAll(selector); // get all links const
                    // do stuff with the links
                    links.forEach(link => {
                        fileName = link.title;
                        filePath = link.pathname;
                        itemCount = dirListA.push(fileName);                      
                    });
                    dirListA.unshift(itemCount);
                    console.log(dirListA.length); //here lenght is OK
                }
            };
            request.send();
            console.log(dirListA);  //array content looks ok
            console.log(dirListA.length); //her lenght is reported as 0 
            return dirListA;
        }

        function fillDropDown(targetDir) {
            var dropList = "<option> dummy </option>";
            var listArr = loadDir(targetDir);
            console.log(listArr); //array content looks ok           
            console.log(listArr.length); // lenght is reported as 0
            console.log(listArr[0]); //undefined
            //both loops are not working not working probably because of zero lenght
            listArr.forEach(function(item){console.log(item)});

            for (var i = 0; i < listArr.length; i++) {
                console.log(listArr[i])
            };
            console.log(dropList);
            document.getElementById("selectFile").innerHTML = dropList;
        }

The console log looks like this

console screen capture

Although it should be possible to do the filemanipulations in the links.foreach loop it feels un elegant and i would have to write the same code several times with small differences for each file manipulation. I would like to know what's going on here and if there is a work around. Declearing the array "dirListA" globally isdoesn't work neighter p.s. first post over here I hope it looks decend.

kelsny
  • 23,009
  • 3
  • 19
  • 48
Switcher
  • 1
  • 1

0 Answers0