HTML and CSS Reference
In-Depth Information
Parameter
Description
You can set this parameter to a JavaScript object whose property names indicate valid HTTP
header names. The property values are then set as header values in the HTTP request.
headers
The parameter refers to a JavaScript object that contains data to be passed to the server usually
via a
POST
request.
data
Indicates the type of the expected response from a
GET
request. Feasible values are text (the
default),
json
,
blob
for binary content, and
document
for an XML object.
responseType
The
WinJS.xhr
object returns a JavaScript
Promise
object so that the developer can easily arrange
any subsequent steps following the asynchronous HTTP operation. When it comes to JavaScript
promises and asynchronous operations, you've used both
then
and
done
functions in previous
chapters, but it's useful to briefly revisit the difference between the two.
Windows 8 JavaScript (WinJS) library asynchronous operations always return a
Promise
object. As
the name may suggest, the object represents the promise of getting some usable data at some point
in the (near) future. So as a developer, you are allowed to specify those next steps using functions
such as
Promise.done
and
Promise.then
. Both functions indicate a future action to perform as soon as
the promised data becomes available. But what's the difference?
Promise.done
and
Promise.then
are exactly the same except that
Promise.done
breaks the chain by
returning
undefined
instead of a
Promise
object. In other words, you could write code such as:
WinJS.xhr(url).then(doThis).then(doThat).done(doAlsoThis);
But you can't write code like this:
WinJS.xhr(url).done(doThis).then(doThat);
In other words, when you use the
done
function, you must be at the end of a chain of instructions.
Handling errors during HTTp requests
An HTTP request may fail for a number of reasons. For example, you may lose your connection
before the request completes, or the request may be refused by the server because it is malformed or
because you didn't provide valid credentials. Finally, the request may hang indefinitely and time out.
How do you deal with all these situations? This is just where the advanced capabilities of JavaScript
Promise
objects come into play.
Both the
done
and
then
functions have the following prototype:
WinJS.xhr({ url: ... }).then(
function completed(request) {
// The request completed successfully.
},
function error(error) {
// The request failed for some reasons.
Search WWH ::
Custom Search