Wednesday, January 18, 2012

Asynchronous Programming Javascript Promises Windows 8

What is "then ()"?-----
kevingadd 125 days ago | link

It's a method with a signature like this:
    var p = doSomethingAsync();
    p.then(function () { alert("hello"); })

this was from:

Asynchronous patterns are becoming more common and more important to moving web programming forward. they can be challenging to work with in JavaScript. To make asynchronous (or async) patterns easier, JavaScript libraries (like jQuery and Dojo) have added an abstraction called promises (or sometimes deferreds).



One pattern is a promise, which represents the result of a potentially long running and not necessarily complete operation. instead of blocking and waiting for the long-running computation to complete, the pattern returns an object which represents the promised result.

An example of this might be making a request to a third-party system where network latency is uncertain. instead of blocking the entire application while waiting, the application is free to do other things until the value is needed. a promise implements a method for registering callbacks for state change notifications, commonly named the then method:

var results = searchTwitter(term).then(filterResults);

At any moment in time, promises can be in one of three states: unfulfilled, resolved or rejected.


—Matt Podwysocki, JavaScript geek and consultant
—Amanda Silver, Program Manager for JavaScript

see Asynchronous Programming in JavaScript with “Promises”

Here's an example in Windows 8 javascript
function databindContact() {
    // Retrieve the control template
    var contactTemplate = WinJS.UI.getControl(document.getElementById("contactTemplate"));
    // Build up the model to display
    var model = {
        firstName: "John",
        lastName: "Doe",
        email: "",
        phone: "+1 415 123 456"
    // Render the databound control
    contactTemplate.render(model).then(function (element) {
        // Inject the control where we need it

One really important concept in the preceding piece of code is the render method of the control template. This method is actually an implicit async call which returns what is called a promise. A promise is a callback method which will hold the result of the method and that you can define through the then method. Here we directly handled the result in an anonymous function

This promise article doesn't use the promise.then syntax:

No comments:

Post a Comment