Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinJS Promise then erroring

After some experimentation, I've ended up with the following code, trying to replicate the C# await functionality:

var promise = new WinJS.Promise(MyFunc())
    .then(function () {
        // Second function which uses data set-up in the first
        MyFunc2();
    });

'MyFunc()' executes correctly, but 'MyFunc2()' does not, and the program crashes. What am I misunderstanding about the Promise object?

(This is using Windows 8)

EDIT:

The full code for MyFunc() is now as follows:

function MyFunc() {
    var foldername = "Folder";
    var filename = "readme.xml";

    var promise = Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(foldername).then(function (folder) {
        folder.getFileAsync(filename).then(function (file) {
            var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings;
            loadSettings.prohibitDtd = false;
            loadSettings.resolveExternals = false;
            Windows.Data.Xml.Dom.XmlDocument.loadFromFileAsync(file, loadSettings).then(function (doc) {
                dataText = doc.getXml();
                xmlDoc = doc;
            }, function (error) {
                output.value = "Error: Unable to load XML file";
                output.style.color = "red";
            }, function (error) {
                output.value = "Error: Unable to load XML file";
                output.style.color = "red";
            })
        })
    });

    return promise;
};

The result now is that 'MyFunc2()' executes before 'MyFunc()' completes. `MyFunc2() uses the global variable xmlDoc, which is therefore undefined at that time.

like image 883
Paul Michaels Avatar asked Dec 05 '25 14:12

Paul Michaels


1 Answers

You should chain all the promises together and then wait on the final promise.

function MyFunc() {
    var promise = Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(foldername).then(function (folder) {
        return folder.getFileAsync(filename);
        }).done(function (file) {
            var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings;
            loadSettings.prohibitDtd = false;
            loadSettings.resolveExternals = false;
            return Windows.Data.Xml.Dom.XmlDocument.loadFromFileAsync(file, loadSettings);
        }).then(function (doc) {
            dataText = doc.getXml();
            xmlDoc = doc;
            return doc; // whatever the result is
        }, function (error) {
            output.value = "Error: Unable to load XML file";
            output.style.color = "red";
        });
    return promise;
}

Then you can chain on the promise returned by MyFunc:

var promise = MyFunc().then(function(doc) { MyFunc2(...); });
like image 136
Raymond Chen Avatar answered Dec 07 '25 03:12

Raymond Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!