简体   繁体   中英

Javascript - How do I return a generic function inside another function?

I would like to print in the console the value of the output variable of the first function, through the second function

In fact it can be seen that within the main function there are two other generic functions; all this confuses my thoughts

 function carica() { document.getElementById('carica').addEventListener('change', function () { var fr = new FileReader(); fr.onload = function () { var output = document.getElementById('output').textContent = fr.result; return output; } fr.readAsText(this.files[0]); return fr.output; }) gestioneElenco(output); } function gestioneElenco(output) { console.log("1 " + output); }

This should work:

function carica() {
    document.getElementById('carica').addEventListener('change', function () {
        var fr = new FileReader();
        fr.onload = function () {
            var output = document.getElementById('output').textContent = fr.result;
            gestioneElenco(output);
        }
        fr.readAsText(this.files[0]);
        return fr.output;
    })
}
function gestioneElenco(output) {
    console.log("1 " + output);
}

Which generic function are you trying to return?

The mistakes you make in the above construct:

return fr.output;

  1. There is no property called output in the FileReader object. In fact, it has result property which is only valid after the FileReader is fully loaded.

  2. Returning anything from an event listener makes it go nowhere

Just call gestioneElenco(output); inside the onLoad function. This will make your second function called soon as the file content is read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM