0

I encounter a problem with asynchronous call using phonegap, because I need to get the return of the following function in order to process the rest of the code.

So I have the following function:

function getFileContent(fileName) {
    var content = null;
    document.addEventListener("deviceready", function() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
            fileSystem.root.getFile("data/" + fileName, null, function(fileEntry) {
                fileEntry.file(function(file) {
                    var reader = new FileReader();
                    reader.onloadend = function(evt) {
                        content = evt.target.result;
                        alert(content);
                    }
                    reader.readAsText(file);
                });
            }, fail);
        }, fail);
    }, false);
   return content;
}

but when I try alert(getFileContent(fileName)); first I get null and then the alert with the content of the file

I have try to add the following line before the return but then nothing is executed:

while (content == null);

I would like to avoid using something like setTimeout because I need to get the response immediately and not after a delay

Alexis
  • 2,149
  • 2
  • 25
  • 39
  • 1
    Whatever you need to perform post reading the file contents should be a part of your callback function (or another function called from the callback function). – SHANK Aug 09 '13 at 07:24

1 Answers1

0

As said by SHANK I must call the final function in the last callback function so I just changed my function to:

function getFileContent(fileName, call) {
    var callBack = call;
    var content = null;
    var args = arguments;
    var context = this;
    document.addEventListener("deviceready", function() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(
                fileSystem) {
            fileSystem.root.getFile("data/" + fileName, null, function(
                    fileEntry) {
                fileEntry.file(function(file) {
                    var reader = new FileReader();
                    reader.onloadend = function(evt) {
                        args = [].splice.call(args, 0);
                        args[0] = evt.target.result;
                        args.splice(1, 1);
                        callBack.apply(context, args);
                    }
                    reader.readAsText(file);
                });
            }, fail);
        }, fail);
    }, false);
}

And now it's working

Alexis
  • 2,149
  • 2
  • 25
  • 39
  • The above code looks very promising and I'm glad it works, but it's not apparent how to call it. What gets passed into getFileContent()? – Kevin MacDonald Feb 21 '14 at 19:47
  • you pass the filename of what you want to read and the function that we be called once everything have been performed (open and read) – Alexis Feb 25 '14 at 16:41