简体   繁体   中英

How do I return a variable from a callback function in javascript?

I need to return the value of tempVar but I can't figure out how to do this since it is the result of a callback. What is the correct way to handle something like this? I'm not really sure how to word this problem. I was hoping it would work by doing something like var tempReturned = readPWFile('filename.txt'); but that doesn't for obvious reasons even if I were to have a 'return' somewhere in the callback. My main goal is to return the results of a txt file to a variable. Can someone point me in the right direction?

function readPWFile(fileName) {
    var tempVar;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
        fileSystem.root.getFile(fileName, null, gotReadFileEntry, fail);
    });

    function gotReadFileEntry(fileEntry) {
        fileEntry.file(gotFile, fail);
    }

    function gotFile(file) {
        readDataUrl(file);
    }

    function readAsText(file) {
        var reader = new FileReader();
        reader.onloadend = function (evt) {
            tempVar = evt.target.result;
        };
        reader.readAsText(file);
    }
}

You should provide a callback through your API which will grant access to the variable by passing it as a callback argument.

Another alternative to use is through the use of promises, which allow you to work on an object which may not have a result yet.

For instance your function declaration should be

function readPWFile(fileName, callback) {

And would be invoked with

readPWFile(filename, function(tempVar) {
     alert("Successfully received tempVar");
});

In essence your code will simply bind this callback function to the reader, rather than using your code. Unless you want to mutate the result in someway of course :

function readPWFile(fileName, callback) {
    ...

    function readAsText(file) {
        var reader = new FileReader();
        // Preference the user's passed in callback function over the previous implementation
        reader.onloadend = callback;
        reader.readAsText(file);
    }
}

A good start is to read up on Node.js. One of Node's objectives is to provide an non-blocking I/O solution, by using callback patterns. So there's a ton of material on callback patterns in the Node.js community.

You can try an other solution

function getContentFile(filePath){

    var FileToOpen = function FileToOpen(filePath)
    {
        if(window.XMLHttpRequest) var obj = new XMLHttpRequest(); //Firefox, Opera,...

        else if(window.ActiveXObject) var obj = new ActiveXObject("Microsoft.XMLHTTP"); //Internet Explorer 

        else return(false);


        if (obj.overrideMimeType) obj.overrideMimeType("text/html"); //Avoids bug with Safari


        obj.open("GET", filePath, false);
        obj.send(null);

        if(obj.readyState == 4) return(obj.responseText);
        else return(false);
    }

    var content = FileToOpen(filePath); 
    return content;
}

I use this function and I read an html file.

and call this function like this

var contentFile = getContentFile(yourFilePath/file.html);

Pass in a callback to be called when the value updates:

function readPWFile(fileName, cb) {
  window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
    fileSystem.root.getFile(fileName, null, gotReadFileEntry, fail);
  });
  function gotReadFileEntry(fileEntry) {
    fileEntry.file(gotFile, fail);
  }
  function gotFile(file) {
    readDataUrl(file);
  }
  function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
      cb(evt.target.result);
    };
    reader.readAsText(file);
  }
}

Usage:

readPWFile("test", function(val) {
  console.debug("Value: " + val);
});

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