Dav*_*vid 0 javascript xmlhttprequest promise winjs
我想在我的应用程序中使用最清晰的代码.所以我决定将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.
}
));
Run Code Online (Sandbox Code Playgroud)
并在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.
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
但我有这个例外:
0x800a138f - JavaScript的运行时错误:无法获取的未定义或为空引用属性"然后"
我想有:的getFoo()完成时启动承诺在view.js做一些东西,并更新视图.我不这样做的正确的方式,但作为C#developper我有一些困难,了解了这种模式.
编辑:有我更新的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它解决了关于"然后",但"回报承诺""回归项目"之前,被称为我的问题.所以我的"来电者"只会得到承诺,而不是他的结果.
我错过了什么 ?
编辑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" });
}
}
Run Code Online (Sandbox Code Playgroud)
更简洁的方法是让函数返回WinJS.xhr().then()的返回值.这样做是返回一个承诺,它将使用内部已完成的处理程序的返回值来实现:
Foo:
{
getFooAsync: function () {
return WinJS.xhr({ url: "http://sampleurl.com" }).then(
function completed(request) {
var xmlElements = request.responseXML;
var parser = new myapp.Parser.Foo();
var items = parser.parse(xmlElements);
return items;
}
));
},
}
Run Code Online (Sandbox Code Playgroud)
然后调用者可以对从getFooAsync获取的promise使用then/done,并且完成的处理程序中的结果将是完成的处理程序返回的项.(你不会在这个函数中使用.done,因为你想要返回一个promise.)
这是指定的行为,然后在承诺-A,以允许链接.有关详细信息,请参阅Windows 8开发人员博客上的帖子,http://blogs.msdn.com/b/windowsappdev/archive/2013/06/11/all-about-promises-for-windows-store-apps -written-in-javascript.aspx.