【发布时间】:2013-01-08 23:53:51
【问题描述】:
有一个代码:
var theContent;
Windows.Storage.PathIO.readTextAsync(filepath).done(function (fileContent) {
theContent= fileContent;
},
function (error) {
});
然后当我想在 Windows.Storage.PathIO.readTextAsync 之外使用“theContent”时, 它不起作用...... theContent 变量根本不包含任何内容。
代码的哪一部分是错误的? 谢谢!
我放了一些造成麻烦的来源。
global.js,其中包含用于共享的命名空间数组变量。 (在 a.js 和 b.js 中)
WinJS.Namespace.define("GLOBAL", {
theList: null
});
a.js 在特定文件中加载文本。
function readTextFromFiles() {
GLOBAL.theList= new WinJS.Binding.List();
for (var i = 0; i < theFileList.length; i++) {
if (theFileList.getAt(i).filepath !== null) {
Windows.Storage.PathIO.readTextAsync(theFileList.getAt(i).filepath).done(function (fileContent) {
var splitted = fileContent.split("\r\n");
for (var j = 0; j < splitted.length; j ++) {
GLOBAL.theList.push({
partA: splitted[j]
});
}
},
function (error) {
});
}
}
}
b.js,它以各种方式使用 GLOBAL.theList
ready: function (element, options) {
new Windows.UI.Popups.MessageDialog("#2 length " + GLOBAL.theList.length, "MESSAGE").showAsync().then();
},
这就是问题所在。 当我调试 a.js 时,我看到 GLOBAL.theList 包含正确的文件文本。但是,当我将页面导航到 b.html(b.js) 时,弹出消息显示“#2 length 0”,这意味着 GLOBAL.theList 不包含任何内容。
- 在页面加载其他 .js 文件之前,我在 default.html 中包含了 global.js。
- 我进行了测试,当我没有使用 Windows.Storage.PathIO.... 承诺时它可以工作。 (当我直接将数据任意放入 GLOBAL.theList 时)
【问题讨论】:
-
Klados,你做错了什么期望
fileContent在.done()表达式执行后立即出现。此时,...readTextAsync()还没有返回任何数据;它返回了一个 promise 的数据。数据将在短时间内异步到达。因此,您对数据的处理必须在.done()处理程序内部。为异步派生的数据设置外部变量(例如theContent)通常没有什么意义。
标签: javascript windows-8 promise