| |||
|
this was from:
http://news.ycombinator.com/item?id=3000598
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).
<snip>
Promises
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);
displayResults(results);
At any moment in time, promises can be in one of three states: unfulfilled, resolved or rejected.
<snip>
—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:
"john.doe@ucodia.fr"
,
phone:
"+1 415 123 456"
};
// Render the databound control
contactTemplate.render(model).then(
function
(element) {
// Inject the control where we need it
contact.appendChild(element);
});
};}
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:
http://blogs.msdn.com/b/rbuckton/archive/2010/01/29/promises-and-futures-in-javascript.aspx
No comments:
Post a Comment