Search code examples
javascriptwinjspromise

readTextAsync in winjs does not always read my file


My question is about readTextAsync and writeTextAsync in the context of windows store applications. I have searched StackOverflow and MSDN and also otherwise Googled extensively.

My code is given below:

Windows.Storage.ApplicationData.current.roamingFolder.getFileAsync("sample.txt")
    .then(
        function(samplefile){
            return Windows.Storage.FileIO.readTextAsync(samplefile)
        },
        function(e){},
        function(samplefile){
            Windows.Storage.FileIO.readTextAsync(samplefile)
        }
    )
    .done(
        function(something){ data = something; },
        function(){},
        function(something){ data = something; }
    );

My problem is that most of the time the file does not get read. When I debug, it gets read intermittently.

It appears to be an issue of not allowing enough time for the async call to complete. I am totally new to Windows app programming and javascript.

I would appreciate any help. Thanks. ravi


Solution

  • Whan you chain many promises you should have one error function at the end where you put your "done".

    In this way you will be able to see if there is an error while it is reading.

    The way you should write it is:

    Windows.Storage.ApplicationData.current.roamingFolder.getFileAsync("sample.txt")
    .then(
        function(samplefile){
            return Windows.Storage.FileIO.readTextAsync(samplefile)
        }
    )
    .done(
        function(data){ //do something with your data, like assign to a list  },
        function(error){ //do something with error },
        function(data){ //do something with your data } //progress function,not sure what you want to do with this
    );
    

    But this call may not be your problem, if you put this code in a normal function and then call it, you will not be able to see the data object because it will be loaded in an asynchronous way.

    You have to process your data inside the done function because if you assing it to an external variable (your data object) like you did, that variable will be empty when you try to use because most likely the done method hasn't occured yet.