Pages

Wednesday 22 August 2012

Windows 8 and HTML Part 5: Fetch Data with WinJS

Windows 8 and HTML Part 1: Simple Example

Finally, we will start to get some data and begin building our application.  Based on Part 4, the logical place to start will be in home.js.  In the ready function for the page, we will use WinJS.xhr() to make an Http request to Twitter, and parse the results.  Making a call using WinJS.xhr() is straightforward in this case. 

WinJS.xhr({ url: "http://search.twitter.com/search.json?q=%23windows8&rpp=100" })

As you can see, we pass on object with the url property set to the Twitter search service.  We will search on the #Windows8 hash tag and request 100 tweets.  If we left this code as shown, our app would make a request to Twitter, but we would never get the results returned.  Why?  WinJS.xhr() is an async operation and will execute on a different thread than the UI thread that called it.  This is accomplished by using a Promise.  If you look at the xhr() return value, you will see that it actually returns a Promise.

To get the results when the Promise completes is async op, we need to call it’s then() or done() function.  You can chain multiple then() functions, because then() returns a promise. You cannot chain more than one done() method, because it returns undefined.  Since we want to parse the results of our search, we would write

WinJS.xhr({ url: "http://search.twitter.com/search.json?q=%23windows8&rpp=100" }).then(
   function(response) {},
   function (error) {},
   function (progress) {}
);

Read full article here

No comments:

Post a Comment

Web Informer Button