1

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);

})();
Sergey K.
  • 24,894
  • 13
  • 106
  • 174
ahoereth
  • 487
  • 1
  • 6
  • 13
  • It doesn't make sense to return results from asynchronous handlers. – Pointy Jun 10 '12 at 13:48
  • If I declare `var results=[]` before using WinJS and returning it afterwards it is not changed at all, so i tried the return thing.. Whats the right way to do it? – ahoereth Jun 10 '12 at 13:58
  • You have to make your API asynchronous. Let a function be passed to your function, and then call it from the "success" handler. – Pointy Jun 10 '12 at 14:10
  • [Here](http://stackoverflow.com/questions/3302702/jquery-return-value-using-ajax-result-on-success) is one of hundreds of other similar StackOverflow questions on the topic. – Pointy Jun 10 '12 at 14:11

1 Answers1

5

You won't be able to get your getData function to return the data itself - this is the nature of asynchronous operations in Javascript and Metro.

The WinJS.xhr function returns a WinJS.Promise object, which represents an asynchronous operation. You should return this Promise to your caller, who can use the then or done methods to register callback functions that will be notified when the operation is complete (in the terminology of Promises, when the Promise is fulfilled).

So, your caller of the getData function would look something like this:

function myFunc() {
    getData().then(function(xhr) {
        // ...do something with the data when it arrives...
    }, function(err) {
        // ...do something with the error
    });
}

Notice that the callbacks are passed the XMLHttpRequest object.

And your getData method becomes something like this:

function getData() {
    return WinJS.xhr({ url: "http://stackoverflow.com" })
}
Adam Freeman
  • 1,184
  • 7
  • 6