-4

I want to use PhoneGap to read a file then return me the data of that file, but when i execute the code, it return before read the file. The code below shows how to read file:

function getData() {
    var fileData = null;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
      function gotFS(fileSystem) {
         fileSystem.root.getFile("data.txt", null, gotFileEntry, fail);
         function gotFileEntry(fileEntry) {
            fileEntry.file(gotFile, fail);
         }
         function gotFile(file){
            readAsText(file);
         }

        function readAsText(file) {
           var reader = new FileReader();
           reader.onloadend = function(evt) {
            fileData = evt.target.result;
                alert(fileData) 
               // this alert is executed after returning the data, so it return the data, but the second alert return null when this is method called.
           };
           reader.readAsText(file);
        }
    }
    return fileData;
}

Now when i call that function, it will return null

var data = getData();
alert(data); // return null
Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68

2 Answers2

1

This is an asynchronous method so you'll have to use a callback.

Change getData so it accepts a callback:

function getData(callback) { ....

Then where you are alerting, do this instead:

if (callback) callback(fileData);

Now you can call your function like so:

var _data;

getData(function(data) { 
 // do stuff with data ...
 _data = data;
 alert(data);
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
  • Thanks for the edit, looks much better now. I wrote the original answer on my mobile phone so it was a bit quick'n'dirty :-) – HaukurHaf Dec 08 '13 at 11:38
0

You can't have synchonously the result of an asynchonous query.

check the first response of that for more details : How do I return the response from an asynchronous call?

Community
  • 1
  • 1