Search code examples
windows-8winjswindows-8.1

Winjs Async call in a Class constructor


I have a Class in WinJS with a property in the contructor. The property calls an async method to read his value.

Here is the code:

var MyClass = WinJS.Class.define(
    // The constructor function.
    function () {
        var self = this;

        Windows.Storage.ApplicationData.current.localFolder.getFolderAsync("MYFOLDER")
        .done(function (folder) {
            self.myFolder = folder;
        },
        function (error) {
            self.myFolder = null;
        });
    },
    // The set of instance members.
    {
        myFolder: null,

    });

And then when I instantiate the Class:

var myClass = new MyClass();

I do this because one I instantiate the class the myClass.myFolder will always be available to me without the need to re-run the code. Now my problem is obviously that myClass.myFolder will not be immediately available after the object has been instantiated.

How can I make sure that I am acessing the myClass.myFolder property only after it has a value?

I could return a promise in the property, but basically I am not sure how to use a promise inside a constructor.


Solution

  • All you need to do in order to have the property be a promise is to assign the result of getFolderAsync to the property.

    var MyClass = WinJS.Class.define(
    // The constructor function.
    function () {
        var self = this;
    
        this.myFolder = Windows.Storage.ApplicationData.current.localFolder.getFolderAsync("MYFOLDER");
    },
    // The set of instance members.
    {
        myFolder: null,
    
    });