See the following line of code:
WinJS.xhr({ url: "http://someurl.com" }).then(
function fulfilled(result)
{
if (result.status === 200)
{
resDiv.style.backgroundColor = "lightGreen";
resDiv.innerText = "Success";
}
});
As far as I understand, when WinJS.xhr has completed whatever it does then execute the anonymous function ‘fulfilled’ with argument ‘result’
Coming from Java/C++ background, I’m extremely confused with how this code works – how is ‘result’ being passed to this function? Where does it say anything about what ‘result’ is? How can I know what type of object ‘result’ is and how it has a ‘status’ member?
I’m going to break my answer into two parts: The first concerns the actual execution model of Javascript, and the second which concerns the high-level expression as written.
The Javascript Execution Model
WinJSevaluates to an object.xhrmember whichWinJS.xhrevaluates to. That member is a function, which we will refer to asAbelow so that we can keep clear what exactly is going on.{ url: "http://someurl.com" }returns an object which we will refer to asB.Bhas a property calledurl.A(B)calls a functionAwith a valueBas an argument. It returns an object that we will refer to asC.Chas a prototype which contains a member namedthen.C.thenhappens to evaluate to a function. That function we will refer to asD.function fulfilled(result) {...}returns a function that we will refer to asE. It can also be referred to asfulfilledbut that fact is not used in this program fragment.D(E)calls a functionDwith a valueEas an argument. Nothing is done with the return value.The high-level view
There are three functions here; one is a callback (called
fulfilled), and the other two may be called “methods”- onexhrof theWinJSglobal object, andthenof a promise object.WinJS.xhr({ url: "http://someurl.com" })creates and returns that promise object. You can convince yourself of this by consulting the documentation.The promise object has a method called
thenwhich registers what you can think of as an event handler for when the promise is done. The valueresult– used in that callback registered inthencomes from whatever is making that promise done by in fact calling the methoddoneon that promise. You don’t see the code that does that because it’s someplace in the implementation ofWinJS.xhr.What
WinJS.xhris doing is performing a network request. When that network request is done it will signal the result of that network request (which according to the documentation is an XMLHttpRequest object) through the promise by calling thedone()method on that promise. That in-turn calls the callback we registered with thethen()method.