经过一些实验,我最终得到了以下代码,尝试复制 C# await 功能:
var promise = new WinJS.Promise(MyFunc())
.then(function () {
// Second function which uses data set-up in the first
MyFunc2();
});
'MyFunc()' 正确执行,但 'MyFunc2()' 没有,程序崩溃。我对 Promise 对象有什么误解?
(这是使用 Windows 8)
编辑:
MyFunc() 的完整代码现在如下:
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;
};
现在的结果是 'MyFunc2()' 在 'MyFunc()' 完成之前执行。`MyFunc2() 使用全局变量 xmlDoc,因此当时未定义。