【发布时间】:2013-07-12 00:36:16
【问题描述】:
我希望在我的应用中包含最清晰的代码。所以我决定将 xhr 调用和解析从 view.js 中分离出来。 为此,我添加了:
在 View.js 中
this._pagePromises.push(myapp.Services.Foo.getFoo()
.then(
function success(results) {
var x = results;
},
function error() {
// TODO - handle the error.
}
));
在 Services.js 中
Foo:
{
getFoo: function () {
WinJS.xhr({ url: "http://sampleurl.com" }).done(
function completed(request) {
//parse request
var obj = myapp.Parser.parse(request);
return obj;
},
function error(request) {
// handle error conditions.
}
);
}
}
但我有这个例外:
0x800a138f - JavaScript 运行时错误:无法获取属性 'then' 未定义或空引用
我想要的是: 在 view.js 中启动 promise 做一些事情并在 getFoo() 完成时更新视图。我这样做的方式不正确,但作为 C# 开发人员,我很难理解这种模式。
编辑: 有我更新的代码:
getFoo: function () {
var promise = WinJS.xhr({ url: myapp.WebServices.getfooUrl() });
promise.done(
function completed(request) {
var xmlElements = request.responseXML;
var parser = new myapp.Parser.foo();
var items = parser.parse(xmlElements);
return items;
},
function error(request) {
// handle error conditions.
}
);
return promise;
}
它解决了我关于 'then' 的问题,但是在“return items”之前调用了“return promise”。所以我的“来电者”只得到了承诺,而不是他的结果。
我错过了什么?
编辑 2: 有正确的方法来做到这一点:
Foo:
{
getFooAsync: function () {
return WinJS.Promise.wrap(this.getXmlFooAsync().then(
function completed(request) {
var xmlElements = request.responseXML;
var parser = new myapp.Parser.Foo();
var items = parser.parse(xmlElements);
return items;
}
));
},
getXmlFooAsync: function () {
return WinJS.xhr({ url: "http://sampleurl.com" });
}
}
【问题讨论】:
标签: javascript xmlhttprequest winjs promise