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.
You should chain all the promises together and then wait on the final promise.
Then you can chain on the promise returned by
MyFunc: