beef up m.deferred docs

This commit is contained in:
Leo Horie 2014-05-07 23:01:27 -04:00
parent dfc10a2fc2
commit 85685f55b0

View file

@ -8,6 +8,12 @@ The deferred object can then *apply* a value by calling either `resolve` or `rej
Each computation function takes a value as a parameter and is expected to return another value, which in turns is forwarded along to the next computation function (or functions) in the tree.
The deferred object returned by `m.deferred` has two methods: `resolve` and `reject`, and one property called `promise`. The methods can be called to dispatch a value to the promise tree. The `promise` property is the root of the promise tree. It has a method `then` which takes a `successCallback` and a `errorCallback` callbacks. Calling the `then` method attaches the computations represented by `successCallback` and `errorCallback` to the promise, which will be called when either `resolve` or `reject` is called. The `then` method returns a child promise, which, itself, can have more child promises, recursively.
The `promise` object is actually a function - specifically, it's an [`m.prop`](mithril.prop.md) getter-setter, which gets populated with the value returned by `successCallback` or `errorCallback` (depending on whether `resolve` or `reject` got called).
Note that Mithril promises are not automatically integrated to its automatic redrawing system. If you wish to use third party asynchronous libraries (for example, `jQuery.ajax`), you should also consider using [`m.startComputation` / `m.endComputation`](mithril.computation.md) if you want views to redraw after requests complete.
---
### Usage
@ -27,6 +33,48 @@ greetAsync()
.then(function(value) {console.log(value)}); //logs "hello world" after 1 second
```
#### Retrieving a value via the getter-setter API
```javascript
//asynchronous service
var greetAsync = function() {
var deferred = m.deferred();
setTimeout(function() {
deferred.resolve("hello");
}, 1000);
return deferred.promise;
};
//asynchronous consumer
var greeting = greetAsync()
var processed = greeting.then(function(value) {return value + " world"})
console.log(greeting()) // undefined - because `deferred.resolve` has not been called yet
setTimeout(function() {
//now `deferred.resolve` has been called
console.log(greeting()) // "hello"
console.log(processed()) // "hello world"
}, 2000)
```
#### Integrating to the Mithril redrawing system
```javascript
//asynchronous service
var greetAsync = function() {
m.startComputation();
var deferred = m.deferred();
setTimeout(function() {
deferred.resolve("hello");
m.endComputation();
}, 1000);
return deferred.promise;
};
```
---
### Differences from Promises/A+