I am playing around with the Windows 8 Metro SDK atm but ran in some trouble using WinJS.xhr.
If instead of returning the WinJS.xhr in the getData function i return some json object everything works fine, but i want to return an json object produced by a xhr request.
What is wrong in my attempt here? Thanks!! 🙂
(function () {
"use strict";
function getData() {
return WinJS.xhr({ url: "http://stackoverflow.com" }).done(
function (request) {
var results = [];
var Item = {
title: "title",
text: "some text goes here"
}
results.push(Item);
return results;
},
function (request) {
var results = [];
results.push({ title: "error", text: "error text" });
return results;
}
);
}
var categoryList = new WinJS.Binding.List(getData());
var publicMembers = { itemList: categoryList };
WinJS.Namespace.define("Data", publicMembers);
})();
You won’t be able to get your
getDatafunction to return the data itself – this is the nature of asynchronous operations in Javascript and Metro.The
WinJS.xhrfunction returns aWinJS.Promiseobject, which represents an asynchronous operation. You should return thisPromiseto your caller, who can use thethenordonemethods to register callback functions that will be notified when the operation is complete (in the terminology of Promises, when thePromiseis fulfilled).So, your caller of the getData function would look something like this:
Notice that the callbacks are passed the XMLHttpRequest object.
And your getData method becomes something like this: