Dominik Adamski
Dominik Adamski

Reputation: 164

readTextAsync WinJS cannot work

I need to read content from file. I have global variable fileDate and I want to put content to this variable, but when I call load method, the variable is undefined.

    var filename = "dataFile.txt";
    var fileDate;

WinJS.UI.Pages.define("index.html", {
        ready: function (element, options) {
            loadDate();
            console.log("main" + fileDate);
            this.fillYearSelect();
        },

  function loadDate() {
        return localFolder.getFileAsync(filename).then(function (file) {
            return Windows.Storage.FileIO.readTextAsync(file).then(function (fileContent) {
                fileDate = fileContent;
                console.log("fileContent " + fileContent);
            },
            function (error) {
                console.log("Błąd odczytu");
            });
        },
        function (error) {
            console.log("Nie znaleziono pliku");
        });
    }

Sorry for my English :)

Upvotes: 1

Views: 45

Answers (1)

KevinM
KevinM

Reputation: 144

Don't forget that javascript is asynchronous, when you call console.log("main" + fileDate), the method loadDate() is not finished, and that is why your fileDate is not defined (yet).

You could use promises to achieve this.

Here is an example based on your code :

var filename = "dataFile.txt";
var fileDate;

var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;

function loadDate() {
    return new Promise(function (onComplete, onError) {
        localFolder.getFileAsync(filename).then(function (file) {

            Windows.Storage.FileIO.readTextAsync(file).then(function (fileContent) {
                fileDate = fileContent;
                console.log("fileContent " + fileContent);

                onComplete(fileDate);
            },
            function (error) {
                console.log("Error on readTextAsync");
                onError(error);
            });
        },
        function (error) {
            console.log("Error on getFileAsync");
            onError(error);
        });
    });
}

Now loadDate()returns a promise, you can now use .then() method to do things when loadDate() is finished.

loadDate().then(function (fileDate) {
        console.log("Content : " + fileDate);
    },
    function (error) {
        console.log(error);
    });

Upvotes: 1

Related Questions