Skip to content
This repository
Newer
Older
100644 2194 lines (1553 sloc) 79.864 kb
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
1 API
2 ===
3
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
4 1. Core
ca9523d8 » briancavalier
2014-03-11 Try arguments only
5 * [when(x)](#when)
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
6 * [when(x, f)](#when)
ca9523d8 » briancavalier
2014-03-11 Try arguments only
7 * [when.try(f, ...args)](#whentry)
0bb0cdc3 » briancavalier
2014-03-11 Add a few layout variation examples
8 * [when.lift(f)](#whenlift)
9 * [when.join(...promises)](#whenjoin)
ca9523d8 » briancavalier
2014-03-11 Try arguments only
10 * [when.promise(resolver)](#whenpromise)
11 * [when.resolve(x)](#whenresolve)
12 * [when.reject(error)](#whenreject)
13 * [when.defer()](#whendefer)
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
14 * [when.isPromiseLike(x)](#whenispromiselike)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
15 1. Promise
ca9523d8 » briancavalier
2014-03-11 Try arguments only
16 * [promise.done(handleResult, handleError)](#promisedone)
17 * [promise.then(onFulfilled)](#promisethen)
18 * [promise.spread(onFulfilledArray)](#promisespread)
29abd5fc » briancavalier
2014-05-14 Add promise.fold to TOC, minor cleanup
19 * [promise.fold(combine, promise2)](#promisefold)
ca9523d8 » briancavalier
2014-03-11 Try arguments only
20 * [promise.catch(onRejected)](#promisecatch)
21 * [promise.finally(cleanup)](#promisefinally)
22 * [promise.yield(x)](#promiseyield)
23 * [promise.else(x)](#promiseelse)
24 * [promise.tap(onFulfilledSideEffect)](#promisetap)
25 * [promise.delay(milliseconds)](#promisedelay)
15b0ef79 » scothis
2014-03-26 Allow custom rejection reason for promise.timeout()
26 * [promise.timeout(milliseconds, reason)](#promisetimeout)
ca9523d8 » briancavalier
2014-03-11 Try arguments only
27 * [promise.inspect()](#promiseinspect)
28 * [promise.with(thisArg)](#promisewith)
29 * [promise.progress(onProgress)](#promiseprogress)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
30 1. Arrays
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
31 * [when.all(array)](#whenall)
32 * [when.settle(array)](#whensettle)
33 * [when.map(array, mapper)](#whenmap)
34 * [when.reduce(array, reducer)](#whenreduce)
35 * [when.reduceRight(array, reducer)](#whenreduceright)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
36 1. Array Races
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
37 * [when.any(array)](#whenany)
38 * [when.some(array, n)](#whensome)
8bfe7cea » briancavalier
2014-03-17 Update verbage around iterate/unfold
39 1. Infinite Promise Sequences
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
40 * [when.iterate(f, condition, handler, seed)](#wheniterate)
41 * [when.unfold(f, condition, handler, seed)](#whenunfold)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
42 1. Objects
43 * when/keys
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
44 * [keys.all(object)](#whenkeys-all)
45 * [keys.map(object, mapper)](#whenkeys-map)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
46 1. Functions
47 * when/function
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
48 * [fn.lift(f)](#fnlift)
49 * [fn.liftAll(object)](#fnliftall)
50 * [fn.call(f, ...args)](#fncall)
51 * [fn.apply(f, argsArray)](#fnapply)
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
52 * when/node
53 * [node.lift(nodeFunction)](#nodelift)
54 * [node.liftAll(object)](#nodeliftall)
55 * [node.call(nodeFunction, ...args)](#nodecall)
56 * [node.apply(nodeFunction, argsArray)](#nodeapply)
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
57 * [node.bindCallback(promise, nodeback)](#nodebindcallback)
58 * [node.liftCallback(callback)](#nodeliftcallback)
59 * [node.createCallback(resolver)](#nodecreatecallback)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
60 * when/callbacks
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
61 * [callbacks.lift(asyncFunction)](#callbackslift)
62 * [callbacks.liftAll(object)](#callbacksliftall)
63 * [callbacks.call(asyncFunction, ...args)](#callbackscall)
64 * [callbacks.apply(asyncFunction, argsArray)](#callbacksapply)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
65 1. [ES6 generators](#es6-generators)
66 * when/generator
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
67 * [generator.lift(g)](#generatorlift)
68 * [generator.call(g, ...args)](#generatorcall)
69 * [generator.apply(g, argsArray)](#generatorapply)
70 1. Task Execution
71 * [when/sequence(tasks, ...args)](#whensequence)
72 * [when/pipeline(tasks, ...args)](#whenpipeline)
73 * [when/parallel(tasks, ...args)](#whenparallel)
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
74 * [when/poll(task, interval, condition [, initialDelay])](#whenpoll)
e23b7db0 » briancavalier
2014-03-11 Add params to all funcs in TOC
75 1. Limiting Concurrency
76 * [when/guard(condition, f)](#whenguard)
9c458800 » briancavalier
2013-04-29 Move guard examples up. Add Guard conditions to TOC
77 * [Guard conditions](#guard-conditions)
fffafd5d » jodal
2014-06-15 Fix broken link in API docs ToC
78 1. [Error types](#error-types)
9eff801c » briancavalier
2013-06-20 Move when/monitor docs to main docs, simplify README and link to docs
79 1. [Debugging promises](#debugging-promises)
f3057ee0 » briancavalier
2014-03-14 Update changelog, add upgrading to 3.0 section to docs
80 1. [Upgrading to 3.0 from 2.x](#upgrading-to-30-from-2x)
f9dae397 » briancavalier
2012-07-24 API doc update
81
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
82 # Core
83
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
84 ## when()
f9dae397 » briancavalier
2012-07-24 API doc update
85
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
86 ```js
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
87 var promise = when(x);
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
88 ```
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
89
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
90 Get a trusted promise for `x`. If `x` is:
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
91
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
92 * a value, returns a promise fulfilled with `x`
93 * a promise, returns `x`.
94 * a foreign thenable, returns a promise that follows `x`
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
95
96
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
97 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
98 var transformedPromise = when(x, f);
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
99 ```
100
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
101 Get a trusted promise by transforming `x` with `f`. If `x` is
102
103 * a value, returns a promise fulfilled with `f(x)`
104 * a promise or thenable, returns a promise that
105 * if `x` fulfills, will fulfill with the result of calling `f` with `x`'s fulfillment value.
106 * if `x` rejects, will reject with the same reason as `x`
ac1963c8 » briancavalier
2012-11-14 See #70. Add info about when() always returning a when.js promise, wh…
107
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
108 `when()` accepts any promise that provides a *thenable* promise--any object that provides a `.then()` method, even promises that aren't fully Promises/A+ compliant, such as jQuery's Deferred. It will assimilate such promises and make them behave like Promises/A+.
fc0ed69f » briancavalier
2012-07-10 Tweaking api doc order
109
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
110 ## when.try
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
111
5e180148 » briancavalier
2014-03-17 Add when.try/when.lift examples
112 **ALIAS:** when.attempt() for non-ES5 environments
113
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
114 ```js
115 var promise = when.try(f /*, arg1, arg2, ...*/);
116 ```
117
118 Calls `f` with the supplied arguments, returning a promise for the result. The arguments may be promises, in which case, `f` will be called after they have fulfilled. The returned promise will fulfill with the successful result of calling `f`. If any argument is a rejected promise, or if `f` fails by throwing or returning a rejected promise, the returned promise will also be rejected.
119
5e180148 » briancavalier
2014-03-17 Add when.try/when.lift examples
120 This can be a great way to kick off a promise chain when you want to return a promise, rather than creating a one manually.
121
122 ```js
123 // Try to parse the JSON, capture any failures in the returned promise
124 // (This will never throw)
125 return when.try(JSON.parse, jsonString);
126 ```
127
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
128 ### See also:
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
129 * [when.lift](#whenlift)
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
130 * [when/node call](#nodecall)
131 * [when/node apply](#nodeapply)
fc0ed69f » briancavalier
2012-07-10 Tweaking api doc order
132
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
133 ## when.lift
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
134
135 ```js
136 var g = when.lift(f);
137 ```
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
138
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
139 Creates a "promisified" version of `f`, which always returns promises (`g` will never throw) and accepts promises or values as arguments. In other words, calling `g(x, y z)` is like calling `when.try(f, x, y, z)` with the added convenience that once you've created `g` you can call it repeatedly or pass it around like any other function. In addition, `g`'s thisArg will behave in a predictable way, like any other function (you can `.bind()` it, or use `.call()` or `.apply()`, etc.).
140
5e180148 » briancavalier
2014-03-17 Add when.try/when.lift examples
141 Like `when.try`, lifting functions provides a convenient way start promise chains without having to explicitly create promises, e.g. `new Promise`
142
143 ```js
144 // Call parse as often as you need now.
145 // It will always return a promise, and will never throw
146 // Errors will be captured in the returned promise.
147 var jsonParse = when.lift(JSON.parse);
148
149 // Now use it wherever you need
150 return jsonParse(jsonString);
151 ```
152
153 `when.lift` correctly handles `this`, so object methods can be lifted as well:
154
155 ```js
156 var parser = {
157 reviver: ...
158 parse: when.lift(function(str) {
159 return JSON.parse(str, this.reviver);
160 });
161 };
162
163 // Now use it wherever you need
164 return parser.parse(jsonString);
165 ```
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
166
167 ### See also:
168 * [when.try](#whentry)
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
169 * [when/node lift](#nodelift)
170 * [when/node liftAll](#nodeliftall)
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
171
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
172 ## when.join
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
173
174 ```js
175 var joinedPromise = when.join(promiseOrValue1, promiseOrValue2, ...);
176 ```
177
178 Return a promise that will fulfill only once *all* the inputs have fulfilled. The value of the returned promise will be an array containing the values of each of the inputs.
179
180 If any of the input promises is rejected, the returned promise will be rejected with the reason from the first one that is rejected.
181
182 ```js
183 // largerPromise will resolve to the greater of two eventual values
184 var largerPromise = when.join(promise1, promise2).then(function (values) {
185 return values[0] > values[1] ? values[0] : values[1];
186 });
187 ```
188
189 ### See also:
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
190 * [when.all](#whenall) - resolving an Array of promises
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
191
192 ## when.promise
193
194 ```js
195 var promise = when.promise(resolver);
196 ```
197
198 Create a [Promise](#promise), whose fate is determined by running the supplied resolver function. The resolver function will be called synchronously, with 3 arguments:
199
200 ```js
201 var promise = when.promise(function(resolve, reject, notify) {
202 // Do some work, possibly asynchronously, and then
203 // resolve or reject. You can notify of progress events
204 // along the way if you want/need.
205
206 resolve(awesomeResult);
207 // or resolve(anotherPromise);
208 // or reject(nastyError);
209 });
210 ```
211
212 * `resolve(promiseOrValue)` - Primary function that seals the fate of the returned promise. Accepts either a non-promise value, or another promise.
213 * When called with a non-promise value, fulfills `promise` with that value.
214 * When called with another promise, e.g. `resolve(otherPromise)`, `promise`'s fate will be equivalent to that that of `otherPromise`.
215 * `reject(reason)` - function that rejects `promise`.
216 * `notify(update)` - function that issues progress events for `promise`.
217
218 ## when.resolve
219
220 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
221 var resolved = when.resolve(x);
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
222 ```
223
161a6073 » briancavalier
2014-03-13 Add ES6 Promise shim docs
224 Get a promise for the supplied `x`. If `x` is already a trusted promise, it is returned. If `x` is a value, the returned promise will be fulfilled with `x`. If `x` is a thenable, the returned promise will follow `x`, adopting its eventual state (fulfilled or rejected).
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
225
226 ## when.reject
227
228 ```js
229 var rejected = when.reject(error);
230 ```
231
232 Create a rejected promise with the supplied error as the rejection reason.
233
234 **DEPRECATION WARNING:** In when.js 2.x, error is allowed to be a promise for an error. In when.js 3.0, error will always be used verbatim as the rejection reason, even if it is a promise.
235
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
236 ## when.defer
237
238 ```js
239 var deferred = when.defer();
c1ea9b54 » briancavalier
2014-03-20 Explicitly discourage the use of when.defer, and point people at alte…
240 ```
241
242 **Note:** The use of `when.defer` is discouraged. In most cases, using [`when.promise`](#whenpromise), [`when.try`](#whentry), or [`when.lift`](#whenlift) provides better separation of concerns.
243
244 Create a `{promise, resolve, reject, notify}` tuple. In certain (rare) scenarios it can be convenient to have access to both the `promise` and it's associated resolving functions.
245
246 The deferred API:
247
248 ```js
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
249 var promise = deferred.promise;
c1ea9b54 » briancavalier
2014-03-20 Explicitly discourage the use of when.defer, and point people at alte…
250
251 // Resolve the promise, x may be a promise or non-promise
252 deferred.resolve(x)
253
254 // Reject the promise with error as the reason
255 deferred.reject(error)
256
257 // Notify promise consumers of a progress update
258 deferred.notify(x)
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
259 ```
260
c1ea9b54 » briancavalier
2014-03-20 Explicitly discourage the use of when.defer, and point people at alte…
261 Note that `resolve`, `reject`, and `notify` all become no-ops after either `resolve` or `reject` has been called the first time.
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
262
fac32f37 » briancavalier
2014-03-11 Clean up defer docs a bit more
263 One common use case for creating a deferred is adapting callback-based functions to promises. In those cases, it's preferable to use the [when/callbacks](#asynchronous-functions) module to [call](#callbackscall) or [lift](#callbackslift) the callback-based functions instead. For adapting node-style async functions, use the [when/node](#node-style-asynchronous-functions) module.
e4b55bd7 » briancavalier
2014-03-11 Add TOC links to updated docs
264
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
265 ## when.isPromiseLike
266
267 ```js
268 var is = when.isPromiseLike(x);
269 ```
270
271 Return true if `x` is an object or function with a `then` method. It does not distinguish trusted when.js promises from other "thenables" (e.g. from some other promise implementation).
272
273 Using `isPromiseLike` is discouraged. In cases where you have an `x` and don't know if it's a promise, typically the best thing to do is to cast it: `var trustedPromise = when(x);` and then use `trustedPromise`.
274
275
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
276 # Promise
277
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
278 A promise is a proxy for a value that isn't available yet allowing you to interact with it as if it is.
2616c27f » briancavalier
2012-09-03 #53 Add info about .then returning a new promise to API docs
279
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
280 ## promise.done
281
282 ```js
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
283 promise.done(handleValue); // returns undefined
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
284 ```
285
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
286 The simplest API for interacting with a promise, `done` consumes the promise's ultimate value if it fulfills, or causes a fatal error with a loud stack trace if it rejects.
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
287
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
288 ```js
bda09fb3 » briancavalier
2014-04-29 Deprecate then's third argument
289 promise.done(handleValue, handleError); // returns undefined
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
290 ```
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
291
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
292 Consume the promise's ultimate value if the promise fulfills, or handle the ultimate error. It will cause a fatal error if either `handleValue` or `handleError` throw or return a rejected promise.
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
293
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
294 Since `done`'s purpose is consumption rather than transformation, `done` always returns `undefined`.
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
295
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
296 One golden rule of promise error handling is:
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
297
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
298 Either `return` the promise, thereby *passing the error-handling buck* to the caller, or call `done` and *assuming responsibility for errors*.
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
299
0bb0cdc3 » briancavalier
2014-03-11 Add a few layout variation examples
300 ### See also
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
301 * [promise.then vs. promise.done](#promisethen-vs-promisedone)
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
302 * [promise.then](#promisethen)
303
304 ## promise.then
f9dae397 » briancavalier
2012-07-24 API doc update
305
2616c27f » briancavalier
2012-09-03 #53 Add info about .then returning a new promise to API docs
306 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
307 var transformedPromise = promise.then(onFulfilled);
308 ```
309
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
310 [Promises/A+ `then`](http://promisesaplus.com). *Transforms* a promise's value by applying a function to the promise's fulfillment value. Returns a new promise for the transformed result.
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
311
312 ```js
bda09fb3 » briancavalier
2014-04-29 Deprecate then's third argument
313 var transformedPromise = promise.then(onFulfilled, onRejected);
314 ```
315
316 `then` may also be used to recover from intermediate errors. However, [`promise.catch`](#promisecatch) is almost always a better, and more readable choice. When `onRejected` is provided, it only handles errors from `promise`, and *will not* handle errors thrown by `onFulfilled`. Compare:
317
318 ```js
319 // Using only then(): onRejected WILL NOT handle errors thrown by onFulfilled
320 var transformedPromise = promise
321 .then(onFulfilled, onRejected);
322
323 // Using catch(): onRejected will handled errors thrown by onFulfilled
324 var transformedPromise = promise
325 .then(onFulfilled)
326 .catch(onRejected);
327
328 // Using catch() is equivalent to:
329 var transformedPromise = promise
330 .then(onFulfilled)
331 .then(void 0, onRejected);
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
332 ```
333
bda09fb3 » briancavalier
2014-04-29 Deprecate then's third argument
334 **DEPRECATED**: `then` may also be used to listen to progress events in a promise chain. Use [`promise.progress`](#promiseprogress) instead.
335
336 ```js
337 // Instead of this:
338 var transformedPromise = promise.then(onFulfilled, onRejected, onProgress);
339
340 // Do this:
341 var transformedPromise = promise
342 .progress(onProgress)
343 .then(onFulfilled)
344 .catch(onRejected)
345 ```
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
346
347 `then` arranges for:
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
348
349 * `onFulfilled` to be called with the value after `promise` is fulfilled, or
350 * `onRejected` to be called with the rejection reason after `promise` is rejected.
bda09fb3 » briancavalier
2014-04-29 Deprecate then's third argument
351 * **DEPRECATED**: `onProgress` to be called with any progress updates issued by `promise`.
2616c27f » briancavalier
2012-09-03 #53 Add info about .then returning a new promise to API docs
352
353 A promise makes the following guarantees about handlers registered in the same call to `.then()`:
354
c3f3d363 » briancavalier
2012-11-12 Update terminology in api doc
355 1. Only one of `onFulfilled` or `onRejected` will be called, never both.
356 1. `onFulfilled` and `onRejected` will never be called more than once.
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
357 1. `onProgress` may be called zero or more times.
2616c27f » briancavalier
2012-09-03 #53 Add info about .then returning a new promise to API docs
358
a6120b3b » briancavalier
2013-11-06 Add cross refs for done and then
359 ### See also
fb395a96 » briancavalier
2013-11-06 Fix link
360 * [Promises/A+](http://promisesaplus.com) for extensive information on the behavior of `then`.
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
361 * [promise.done](#promisedone)
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
362 * [promise.spread](#promisespread)
bda09fb3 » briancavalier
2014-04-29 Deprecate then's third argument
363 * [promise.progress](#promiseprogress)
163965c8 » briancavalier
2013-10-07 Fix doc typo, add link to Promises/A+ for more info on behavior of th…
364
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
365 ## promise.spread
d08bbb8f » briancavalier
2013-11-03 Add jsdoc and api docs for promise.done. Expand Debugging Promises
366
367 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
368 var transformedPromise = promise.spread(onFulfilledArray);
d08bbb8f » briancavalier
2013-11-03 Add jsdoc and api docs for promise.done. Expand Debugging Promises
369 ```
370
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
371 Similar to [`then`](#promisethen), but calls `onFulfilledArray` with promise's value, which is assumed to be an array, as its argument list. It's essentially a shortcut for:
3aa3ef58 » briancavalier
2013-11-06 Finish docs for done()
372
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
373 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
374 // Wrapping onFulfilledArray
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
375 promise.then(function(array) {
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
376 return onFulfilledArray.apply(undefined, array);
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
377 });
378 ```
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
379
cf21190e » jenius
2014-05-08 add documentation
380 ## promise.fold
381
382 ```js
6ac7b070 » briancavalier
2014-05-14 Revise promise.fold api docs slightly
383 var resultPromise = promise2.fold(combine, promise1)
cf21190e » jenius
2014-05-08 add documentation
384 ```
385
6ac7b070 » briancavalier
2014-05-14 Revise promise.fold api docs slightly
386 Combine `promise1` and `promise2` to produce a `resultPromise`. The `combine` function will be called once both `promise1` and `promise2` have fulfilled: `combine(promise1, promise2)`, and like `then` et al, it may return a promise or a value.
387
388 Just as `promise.then` allows you to easily re-use existing one-argument functions to transform promises, `promise.fold` allows you to reuse two-argument functions. It can also be useful when you need to thread one extra piece of information into a promise chain, *without* having to capture it in a closure or use `promise.with`.
d75ab1c0 » briancavalier
2014-05-13 Update versions. Expand promise.fold docs. For now, support sparse ar…
389
390 For, example, with an existing `sum` function, you can easily sum the value of two promises:
391
392 ```js
393 function sum(x, y) {
394 return x + y;
395 }
396
6ac7b070 » briancavalier
2014-05-14 Revise promise.fold api docs slightly
397 var promiseFor3 = when(3);
398
399 var promiseFor5 = promiseFor3.fold(sum, promiseFor2);
400
401 // Of course, it accepts values as well:
402 var promiseFor5 = promiseFor3.fold(sum, 2);
d75ab1c0 » briancavalier
2014-05-13 Update versions. Expand promise.fold docs. For now, support sparse ar…
403 ```
404
405 Or get object properties or array values:
406
407 ```js
6ac7b070 » briancavalier
2014-05-14 Revise promise.fold api docs slightly
408 function get(key, object) {
409 return object[key];
d75ab1c0 » briancavalier
2014-05-13 Update versions. Expand promise.fold docs. For now, support sparse ar…
410 }
411
29abd5fc » briancavalier
2014-05-14 Add promise.fold to TOC, minor cleanup
412 when({ name: 'Bob' })
d75ab1c0 » briancavalier
2014-05-13 Update versions. Expand promise.fold docs. For now, support sparse ar…
413 .fold(get, 'name')
414 .done(console.log); // logs 'Bob'
415
29abd5fc » briancavalier
2014-05-14 Add promise.fold to TOC, minor cleanup
416 when(['a', 'b', 'c'])
d75ab1c0 » briancavalier
2014-05-13 Update versions. Expand promise.fold docs. For now, support sparse ar…
417 .fold(get, 1)
418 .done(console.log); // logs 'b'
419 ```
420
421 In both cases, `sum` and `get` are generic, *reusable* functions, and no closures were required.
cf21190e » jenius
2014-05-08 add documentation
422
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
423 ## promise.catch
a6120b3b » briancavalier
2013-11-06 Add cross refs for done and then
424
3c118cb9 » briancavalier
2013-12-02 Update docs with catch/finally aliases
425 **ALIAS:** otherwise() for non-ES5 environments
f9dae397 » briancavalier
2012-07-24 API doc update
426
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
427 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
428 var recoveredPromise = promise.catch(onRejected);
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
429 ```
430
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
431 In it's simplest form, `catch` arranges to call `onRejected` on the promise's rejection reason if it is rejected.
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
432
433 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
434 var recoveredPromise = promise.catch(predicate, onRejected);
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
435 ```
fc0ed69f » briancavalier
2012-07-10 Tweaking api doc order
436
0bb0cdc3 » briancavalier
2014-03-11 Add a few layout variation examples
437 If you also supply a `predicate`, you can `catch` only errors matching the predicate. This allows much more precise error handling. The `predicate` can be either an `Error` constructor, like `TypeError`, `ReferenceError`, or any custom error type (its `prototype` must be `instanceof Error`), or it can be a function that returns a boolean.
438
439 ```js
440 promise.then(function() {
441 throw new CustomError('oops!');
442 }).catch(CustomError, function(e) {
443 // Only catch CustomError instances
444 // all other types of errors will propagate automatically
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
445 }).catch(function(e) {
446 // Catch other errors
0bb0cdc3 » briancavalier
2014-03-11 Add a few layout variation examples
447 })
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
448 ```
449
450 Doing this in synchronous code is more clumsy, requiring `instanceof` checks inside a `catch` block:
451
452 ```js
453 try {
454 throw new CustomError('oops!');
455 } catch(e) {
456 if(e instanceof CustomError) {
457 // Handler CustomError instances
458 } else {
459 // Handle other errors
460 }
461 }
462 ```
0bb0cdc3 » briancavalier
2014-03-11 Add a few layout variation examples
463
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
464 ### See also:
465 * [promise.finally](#promisefinally)
466
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
467 ## promise.finally
3c118cb9 » briancavalier
2013-12-02 Update docs with catch/finally aliases
468
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
469 **ALIAS:** `ensure()` for non-ES5 environments
fc0ed69f » briancavalier
2012-07-10 Tweaking api doc order
470
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
471 ```js
8210980d » briancavalier
2014-05-19 Fix and improve promise.finally docs. See #320
472 var promise2 = promise1.finally(cleanup);
fc0ed69f » briancavalier
2012-07-10 Tweaking api doc order
473 ```
474
8210980d » briancavalier
2014-05-19 Fix and improve promise.finally docs. See #320
475 Finally allows you to execute "cleanup" type tasks in a promise chain. It arranges for `cleanup` to be called, *with no arguments*, when `promise1` is either fulfilled or rejected. It behaves similarly the synchronous `finally` statement:
476
477 * If `promise1` fulfills, and `cleanup` returns successfully, `promise2` will fulfill with the same value as `promise1`.
478 * If `promise1` rejects, and `cleanup` returns successfully, `promise2` will reject with the same reason as `promise1`.
479 * If `promise1` rejects, and `cleanup` throws or returns a rejected promise, `promise2` will reject with the thrown exception or rejected promise's reason.
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
480
3c118cb9 » briancavalier
2013-12-02 Update docs with catch/finally aliases
481 When combined with `promise.catch`, `promise.finally` allows you to write code that is similar to the familiar synchronous `catch`/`finally` pair. Consider the following synchronous code:
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
482
483 ```js
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
484 try {
485 return doSomething(x);
486 } catch(e) {
487 return handleError(e);
488 } finally {
489 cleanup();
490 }
491 ```
492
3c118cb9 » briancavalier
2013-12-02 Update docs with catch/finally aliases
493 Using `promise.finally`, similar asynchronous code (with `doSomething()` that returns a promise) can be written:
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
494
495 ```js
496 return doSomething()
3c118cb9 » briancavalier
2013-12-02 Update docs with catch/finally aliases
497 .catch(handleError)
498 .finally(cleanup);
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
499 ```
500
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
501 ### See also:
502 * [promise.catch](#promisecatch) - intercept a rejected promise
503
504 ## promise.yield
4af946ab » briancavalier
2012-11-15 Docs for promise.yield
505
506 ```js
1866056a » skiadas
2013-07-04 Clarify the behavior of promise.yield. Fixes #164
507 originalPromise.yield(promiseOrValue);
4af946ab » briancavalier
2012-11-15 Docs for promise.yield
508 ```
509
1866056a » skiadas
2013-07-04 Clarify the behavior of promise.yield. Fixes #164
510 Returns a new promise:
4af946ab » briancavalier
2012-11-15 Docs for promise.yield
511
1866056a » skiadas
2013-07-04 Clarify the behavior of promise.yield. Fixes #164
512 1. If `originalPromise` is rejected, the returned promise will be rejected with the same reason
513 2. If `originalPromise` is fulfilled, then it "yields" the resolution of the returned promise to promiseOrValue, namely:
514 1. If `promiseOrValue` is a value, the returned promise will be fulfilled with `promiseOrValue`
515 2. If `promiseOrValue` is a promise, the returned promise will be:
516 - fulfilled with the fulfillment value of `promiseOrValue`, or
517 - rejected with the rejection reason of `promiseOrValue`
4af946ab » briancavalier
2012-11-15 Docs for promise.yield
518
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
519 In other words, it's much like:
4af946ab » briancavalier
2012-11-15 Docs for promise.yield
520
521 ```js
1866056a » skiadas
2013-07-04 Clarify the behavior of promise.yield. Fixes #164
522 originalPromise.then(function() {
4af946ab » briancavalier
2012-11-15 Docs for promise.yield
523 return promiseOrValue;
524 });
525 ```
f9dae397 » briancavalier
2012-07-24 API doc update
526
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
527 ### See also:
528 * [promise.else](#promiseelse) - return a default value when promise rejects
529
530 ## promise.else
531
532 **ALIAS:** `orElse()` for non-ES5 environments
533
534 ```js
535 var p1 = doAyncOperationThatMightFail();
536 return p1.else(defaultValue);
537 ```
538
539 If a promise is rejected, `else` catches the rejection and resolves the returned promise with a default value. This is a shortcut for manually `catch`ing a promise and returning a different value, as such:
540
541 ```js
542 var p1 = doAyncOperationThatMightFail();
543 return p1.catch(function() {
544 return defaultValue;
545 });
546 ```
547
548 ### See also:
549 * [promise.catch](#promisecatch) - intercept a rejected promise
550 * [promise.tap](#promisetap) - execute a side effect in a promise chain
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
551 * [promise.yield](#promiseyield) - execute a side effect in a promise chain
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
552
553 ## promise.tap
56281dff » briancavalier
2013-08-07 Fix #181. Add promise.tap, unit tests, and docs
554
555 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
556 var promise2 = promise1.tap(onFulfilledSideEffect);
56281dff » briancavalier
2013-08-07 Fix #181. Add promise.tap, unit tests, and docs
557 ```
558
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
559 Executes a function as a side effect when `promise` fulfills. Returns a new promise:
56281dff » briancavalier
2013-08-07 Fix #181. Add promise.tap, unit tests, and docs
560
561 1. If `promise` fulfills, `onFulfilledSideEffect` is executed:
562 - If `onFulfilledSideEffect` returns successfully, the promise returned by `tap` fulfills with `promise`'s original fulfillment value. That is, `onfulfilledSideEffect`'s result is discarded.
563 - If `onFulfilledSideEffect` throws or returns a rejected promise, the promise returned by `tap` rejects with the same reason.
564 2. If `promise` rejects, `onFulfilledSideEffect` is *not* executed, and the promise returned by `tap` rejects with `promise`'s rejection reason.
565
566 These are equivalent:
567
568 ```js
569 // Using only .then()
570 promise.then(function(x) {
571 doSideEffectsHere(x);
572 return x;
573 });
574
575 // Using .tap()
576 promise.tap(doSideEffectsHere);
577 ```
578
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
579 ### See also:
580 * [promise.catch](#promisecatch) - intercept a rejected promise
581 * [promise.else](#promiseelse) - return a default value when promise rejects
582
583 ## promise.delay
67673f70 » briancavalier
2012-11-20 Docs for promise.apply
584
585 ```js
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
586 var delayedPromise = promise.delay(milliseconds);
67673f70 » briancavalier
2012-11-20 Docs for promise.apply
587 ```
588
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
589 Create a new promise that will, after `milliseconds` delay, fulfill with the same value as `promise`. If `promise` rejects, `delayedPromise` will be rejected immediately.
67673f70 » briancavalier
2012-11-20 Docs for promise.apply
590
591 ```js
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
592 var delayed;
593
594 // delayed is a pending promise that will become fulfilled
595 // in 1 second with the value "hello"
596 delayed = when('hello').delay(1000);
597
598 // delayed is a pending promise that will become fulfilled
599 // 1 second after anotherPromise resolves, or will become rejected
600 // *immediately* after anotherPromise rejects.
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
601 delayed = promise.delay(1000);
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
602
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
603 // Do something 1 second after promise resolves
604 promise.delay(1000).then(doSomething).catch(handleRejection);
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
605 ```
67673f70 » briancavalier
2012-11-20 Docs for promise.apply
606
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
607 ### See also:
608 * [promise.timeout](#promisetimeout)
609
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
610 ## promise.timeout
611
612 ```js
15b0ef79 » scothis
2014-03-26 Allow custom rejection reason for promise.timeout()
613 var timedPromise = promise.timeout(milliseconds, reason);
67673f70 » briancavalier
2012-11-20 Docs for promise.apply
614 ```
615
b40cb67d » briancavalier
2014-05-01 Update promise.timeout docs, add TimeoutError docs
616 Create a new promise that will reject with a [`TimeoutError`](#timeouterror) or a custom `reason` after a timeout if `promise` does not fulfill or reject beforehand.
15b0ef79 » scothis
2014-03-26 Allow custom rejection reason for promise.timeout()
617
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
618 ```js
619 var node = require('when/node');
620
621 // Lift fs.readFile so it returns promises
622 var readFile = node.lift(fs.readFile);
623
624 // Try to read the file, but timeout if it takes too long
625 function readWithTimeout(path) {
626 return readFile(path).timeout(500);
627 }
628 ```
629
b40cb67d » briancavalier
2014-05-01 Update promise.timeout docs, add TimeoutError docs
630 You can [pattern-match using `catch`](#promisecatch) to specifically handle `TimeoutError`s:
631
632 ```js
633 var when = require('when');
634
635 var p = readWithTimeout('/etc/passwd')
636 .catch(when.TimeoutError, handleTimeout) // handle only TimeoutError
637 .catch(handleFailure) // handle other errors
638 ```
639
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
640 ### See also:
641 * [promise.delay](#promisedelay)
642
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
643 ## promise.inspect
ffd54ae0 » briancavalier
2013-05-01 Add docs for promise.inspect
644
645 ```js
646 var status = promise.inspect();
647 ```
648
649 Returns a snapshot descriptor of the current state of `promise`. This descriptor is *not live* and will not update when `promise`'s state changes. The descriptor is an object with the following properties. When promise is:
650
651 * pending: `{ state: 'pending' }`
652 * fulfilled: `{ state: 'fulfilled', value: <promise's fulfillment value> }`
653 * rejected: `{ state: 'rejected', reason: <promise's rejection reason> }`
654
655 While there are use cases where synchronously inspecting a promise's state can be helpful, the use of `inspect` is discouraged. It is almost always preferable to simply use `when()` or `promise.then` to be notified when the promise fulfills or rejects.
656
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
657 ### See also:
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
658 * [when.settle](#whensettle) - settling an Array of promises
ffd54ae0 » briancavalier
2013-05-01 Add docs for promise.inspect
659
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
660 ## promise.with
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
661
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
662 **ALIAS:** `withThis()` for non-ES5 environments
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
663
664 ```js
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
665 var boundPromise = promise.with(object);
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
666 ```
667
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
668 Creates a new promise that follows `promise`, but which will invoke its handlers with their `this` set to `object`. Normally, promise handlers are invoked with no specific `thisArg`, so `with` can be very useful when bridging promises to object-oriented patterns and libraries.
9e29a668 » briancavalier
2013-03-11 Close #103. Implement promise.ensure, deprecate promise.always. API d…
669
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
670 **NOTE:** Promises returned from `with`/`withThis` are NOT Promises/A+ compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
e7690353 » jenius
2014-01-24 add docs for promise.else, close #243
671
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
672 For example:
e7690353 » jenius
2014-01-24 add docs for promise.else, close #243
673
674 ```js
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
675 function Thing(value, message) {
676 this.value = value;
677 this.message = message;
678 }
e7690353 » jenius
2014-01-24 add docs for promise.else, close #243
679
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
680 Thing.prototype.doSomething = function(x) {
681 var promise = doAsyncStuff(x);
682 return promise.with(this) // Set thisArg to this thing instance
683 .then(this.addValue) // Works since addValue will have correct thisArg
684 .then(this.format); // all subsequent promises retain thisArg
685 };
e7690353 » jenius
2014-01-24 add docs for promise.else, close #243
686
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
687 Thing.prototype.addValue = function(y) {
688 return this.value + y;
689 };
e7690353 » jenius
2014-01-24 add docs for promise.else, close #243
690
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
691 Thing.prototype.format = function(result) {
692 return this.message + result;
693 };
e7690353 » jenius
2014-01-24 add docs for promise.else, close #243
694
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
695 // Using it
696 var thing = new Thing(41, 'The answer is ');
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
697
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
698 thing.doSomething(1)
699 .with(console) // Re-bind thisArg now to console
700 .then(console.log); // Logs 'The answer is 42'
701
702 ```
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
703
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
704 All promises created from `boundPromise` will also be bound to the same thisArg until `with` is used to re-bind or *unbind* it. In the previous example, the promise returned from `thing.doSomething` still has its thisArg bound to `thing`. That may not be what you want, so you can *unbind* it just before returning:
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
705
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
706 ```js
707 Thing.prototype.doSomething = function(x) {
708 var promise = doAsyncStuff(x);
709 return promise.with(this)
710 .then(this.addValue)
711 .then(this.format)
712 .with(); // Unbind thisArg
713 };
714 ```
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
715
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
716 ## promise.progress
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
717
718 ```js
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
719 promise.progress(onProgress);
720 ```
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
721
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
722 Registers a handler for progress updates from `promise`. It is a shortcut for:
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
723
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
724 ```js
725 promise.then(void 0, void 0, onProgress);
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
726 ```
727
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
728 ### Notes on Progress events
729
730 Progress events are not specified in Promises/A+ and are optional in Promises/A. They have proven to be useful in practice, but unfortunately, they are also underspecified, and there is no current *de facto* or agreed-upon behavior in the promise implementor community.
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
731
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
732 In when.js, progress events will be propagated through a promise chain:
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
733
734 1. In the same way as resolution and rejection handlers, your progress handler *MUST* return a progress event to be propagated to the next link in the chain. If you return nothing, *undefined will be propagated*.
735 1. Also in the same way as resolutions and rejections, if you don't register a progress handler (e.g. `.then(handleResolve, handleReject /* no progress handler */)`), the update will be propagated through.
736 1. **This behavior will likely change in future releases:** If your progress handler throws an exception, the exception will be propagated to the next link in the chain. The best thing to do is to ensure your progress handlers do not throw exceptions.
737 1. **Known Issue:** If you allow an exception to propagate and there are no more progress handlers in the chain, the exception will be silently ignored. We're working on a solution to this.
738
739 This gives you the opportunity to *transform* progress events at each step in the chain so that they are meaningful to the next step. It also allows you to choose *not* to transform them, and simply let them propagate untransformed, by not registering a progress handler.
740
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
741 Here is an example:
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
742
743 ```js
744 function myProgressHandler(update) {
745 logProgress(update);
746 // Return a transformed progress update that is
747 // useful for progress handlers of the next promise!
748 return update + 1;
749 }
750
751 function myOtherProgressHandler(update) {
752 logProgress(update);
753 }
754
755 var d = when.defer();
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
756 d.promise.then(undefined, undefined, myProgressHandler);
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
757
758 var chainedPromise = d.promise.then(doStuff);
18859e87 » briancavalier
2012-11-15 Improve when() and .then() docs and include basic information about h…
759 chainedPromise.then(undefined, undefined, myOtherProgressHandler);
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
760
761 var update = 1;
63c16831 » briancavalier
2013-02-17 Close #106. Add deprecation notice for progress(), prefer notify()
762 d.notify(update);
a26071a6 » briancavalier
2012-10-26 Add info about experimental progress propagation
763
764 // Results in:
765 // logProgress(1);
766 // logProgress(2);
767 ```
768
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
769 # Arrays
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
770
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
771 ## when.all
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
772
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
773 ```js
474ea1bd » briancavalier
2013-03-01 Remove when.chain docs. Minor tweaks. Discourage use of callback args…
774 var promise = when.all(array)
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
775 ```
776
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
777 Where:
778
779 * array is an Array *or a promise for an array*, which may contain promises and/or values.
780
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
781 Return a promise that will resolve only once all the items in `array` have resolved. The resolution value of the returned promise will be an array containing the resolution values of each of the items in `array`.
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
782
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
783 If any of the promises is rejected, the returned promise will be rejected with the rejection reason of the first promise that was rejected.
784
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
785 ### See also:
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
786 * [when.join](#whenjoin)
787 * [when.settle](#whensettle)
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
788
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
789 ## when.map
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
790
791 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
792 var promise = when.map(array, mapper)
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
793 ```
794
795 Where:
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
796
a035e59e » briancavalier
2012-10-15 Added docs for when.join, plus more docs cleanup
797 * array is an Array *or a promise for an array*, which may contain promises and/or values.
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
798
4606d471 » briancavalier
2013-04-29 Add when.settle docs
799 Traditional array map function, similar to `Array.prototype.map()`, but allows input to contain promises and/or values, and mapFunc may return either a value or a promise.
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
800
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
801 If any of the promises is rejected, the returned promise will be rejected with the rejection reason of the first promise that was rejected.
802
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
803 The map function should have the signature:
804
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
805 ```js
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
806 mapFunc(item)
807 ```
808
809 Where:
810
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
811 * `item` is a fully resolved value
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
812
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
813 ## when.reduce
814 ## when.reduceRight
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
815
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
816 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
817 var promise = when.reduce(array, reducer [, initialValue])
818 var promise = when.reduceRight(array, reducer [, initialValue])
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
819 ```
820
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
821 Where:
822
823 * array is an Array *or a promise for an array*, which may contain promises and/or values.
824
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
825 Traditional array reduce function, similar to `Array.prototype.reduce()` and `Array.prototype.reduceRight()`, but input may contain promises and/or values, and reduceFunc may return either a value or a promise, *and* initialValue may be a promise for the starting value.
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
826
827 The reduce function should have the signature:
828
c7b882a7 » briancavalier
2012-07-10 Added when/timeout and when/delay
829 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
830 reducer(currentResult, value, index, total)
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
831 ```
832
833 Where:
834
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
835 * `currentResult` is the current accumulated reduce value
836 * `value` is the fully resolved value at `index` in `array`
837 * `index` is the *basis* of `value` ... practically speaking, this is the array index of the array corresponding to `value`
838 * `total` is the total number of items in `array`
8d43875b » briancavalier
2012-06-26 Moving api docs to straight markdown file in docs dir. Trimming down …
839
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
840 ```js
841 // sum the eventual values of several promises
842 var sumPromise = when.reduce(inputPromisesOrValues, function (sum, value) {
843 return sum += value;
844 }, 0);
845 ```
846
847 If any of the promises is rejected, the returned promise will be rejected with the rejection reason of the first promise that was rejected.
848
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
849 ## when.settle
4606d471 » briancavalier
2013-04-29 Add when.settle docs
850
851 ```js
852 var promise = when.settle(array);
853 ```
854
cdc1df12 » briancavalier
2013-04-29 Add initial docs for when/guard. See #116
855 Returns a promise for an array containing the same number of elements as the input array. Each element is a descriptor object describing of the outcome of the corresponding element in the input. The returned promise will only reject if `array` itself is a rejected promise. Otherwise, it will always fulfill with an array of descriptors. This is in contrast to [when.all](#whenall), which will reject if any element of `array` rejects.
4606d471 » briancavalier
2013-04-29 Add when.settle docs
856
857 If the corresponding input promise is:
858
859 * fulfilled, the descriptor will be: `{ state: 'fulfilled', value: <fulfillmentValue> }`
436b18bf » briancavalier
2013-04-29 Fix rejected descriptor reason
860 * rejected, the descriptor will be: `{ state: 'rejected', reason: <rejectionReason> }`
4606d471 » briancavalier
2013-04-29 Add when.settle docs
861
862 ```js
863 // Process all successful results, and also log all errors
864
865 // Input array
29abd5fc » briancavalier
2014-05-14 Add promise.fold to TOC, minor cleanup
866 var array = [when.reject(1), 2, when(3), when.reject(4)];
4606d471 » briancavalier
2013-04-29 Add when.settle docs
867
868 // Settle all inputs
869 var settled = when.settle(array);
870
871 // Logs 1 & 4 and processes 2 & 3
872 settled.then(function(descriptors) {
873 descriptors.forEach(function(d) {
874 if(d.state === 'rejected') {
875 logError(d.reason);
876 } else {
877 processSuccessfulResult(d.value);
878 }
879 });
880 });
881 ```
882
883 ### See also:
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
884 * [when.all](#whenall)
885 * [promise.inspect](#inspect)
4606d471 » briancavalier
2013-04-29 Add when.settle docs
886
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
887 # Objects
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
888
32f98b40 » briancavalier
2013-03-08 Remove docs for keys.reduce()
889 the `when/keys` module provides `all()`, and `map()` for working with object keys, for the times when organizing promises in a hash using object keys is more convenient than using an array.
890
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
891 ## when/keys all
892
893 ```js
894 var promise = keys.all(object)
895 ```
896
897 Where:
898
899 * object is an Object *or a promise for an Object*, whose keys represent promises and/or values.
900
901 Return a promise that will resolve only once *all* the items in `object` have resolved. The resolution value of the returned promise will be an object containing the resolved key-value pairs of each of the items in `object`.
902
903 If any of the promises is rejected, the returned promise will be rejected with the rejection reason of the first promise that was rejected.
904
905 ### See also:
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
906 * [when.all](#whenall)
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
907
908 ## when/keys map
909
910 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
911 var promise = keys.map(object, mapper)
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
912 ```
913
914 Where:
915
916 * object is an Object *or a promise for an Object*, whose keys represent promises and/or values.
917
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
918 Similar to `when.map`, but for object keys, returns a promise for the key-mappedValue pairs by applying `mapper` to every value. `mapper` may return either a promise or a value.
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
919
920 If any of the promises is rejected, the returned promise will be rejected with the rejection reason of the first promise that was rejected.
921
922 The map function should have the signature:
923
924 ```js
925 mapFunc(value)
926 ```
927
928 Where:
929
930 * `value` is a fully resolved value
931
932 ### See also:
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
933 * [when.map](#whenmap)
bb8970e2 » briancavalier
2013-03-07 Add docs and JSDoc
934
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
935 # Array Races
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
936
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
937 The *competitive race* pattern may be used if one or more of the entire possible set of *eventual outcomes* are sufficient to resolve a promise.
938
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
939 ## when.any
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
940
941 ```js
474ea1bd » briancavalier
2013-03-01 Remove when.chain docs. Minor tweaks. Discourage use of callback args…
942 var promise = when.any(array)
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
943 ```
944
b87c726b » briancavalier
2014-06-17 Promote race to when.race public API. Add docs
945 A competitive race that allows one winner. The returned promise will:
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
946
f9657ecf » briancavalier
2014-03-12 Update any/some/race docs based on suggestions from @kfranqueiro. Tha…
947 * fulfill as soon as any one of the input promises fulfills, with the value of the fulfilled input promise, *or*
aa8a86a8 » briancavalier
2014-06-16 Make some/any reject if race is unwinnable due to too few inputs
948 * reject:
949 * with a `RangeError` if the input array is empty--i.e. it is impossible to have one winner.
950 * with an array of all the rejection reasons, if the input array is non-empty, and *all* input promises reject.
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
951
b87c726b » briancavalier
2014-06-17 Promote race to when.race public API. Add docs
952 ### See also:
953 * [when.race](#whenrace)
954 * [when.some](#whensome)
955
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
956 ## when.some
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
957
7064d56e » briancavalier
2014-05-14 Add deprecation notices to api docs for when.some and when/callbacks.…
958 **DEPRECATED**
959
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
960 ```js
1264d5f0 » briancavalier
2014-03-11 Revised docs for core, promise, arrays, object keys, and races
961 var promise = when.some(array, n)
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
962 ```
963
b87c726b » briancavalier
2014-06-17 Promote race to when.race public API. Add docs
964 A competitive race that requires `n` winners. The returned promise will
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
965
f9657ecf » briancavalier
2014-03-12 Update any/some/race docs based on suggestions from @kfranqueiro. Tha…
966 * fulfill when `n` promises are fulfilled with an array containing the values of the fulfilled input promises, *or*
aa8a86a8 » briancavalier
2014-06-16 Make some/any reject if race is unwinnable due to too few inputs
967 * reject:
968 * with a `RangeError` if the input contains fewer than `n` items--i.e. it is impossible to have `n` winners.
969 * with an array containing the reasons of the rejected input promises when it becomes impossible for `n` promises to become fulfilled (ie when `(array.length - n) + 1` reject).
168338c3 » briancavalier
2012-10-26 See #60. Docs for any/some() competitive races
970
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
971 ```js
f9657ecf » briancavalier
2014-03-12 Update any/some/race docs based on suggestions from @kfranqueiro. Tha…
972 // ping all of the p2p servers and fail if at least two don't respond
973 var remotes = [ping('p2p.cdn.com'), ping('p2p2.cdn.com'), ping('p2p3.cdn.com')];
974 when.some(remotes, 2).done(itsAllOk, failGracefully);
ccee2f39 » unscriptable
2013-02-19 update doc sections with some introductory text and add a few examples
975 ```
976
b87c726b » briancavalier
2014-06-17 Promote race to when.race public API. Add docs
977 ### See also:
978 * [when.any](#whenany)
979
980 ## when.race
981
982 ```js
983 var promise = when.race(array);
984 ```
985
986 A competitive race to settle. The returned promise will settle in the same way as the earliest promise in `array` to settle. That is, it will
987
988 * fulfill if the earliest promise in array fulfills, with the same value, *or*
989 * reject if the earliest promise in array rejects, with the same reason.
990
991 **WARNING:** As per the ES6 spec, the returned promise will *remain pending forever* if `array` is empty.
992
993 ### See also:
994 * [when.any](#whenany)
995
8bfe7cea » briancavalier
2014-03-17 Update verbage around iterate/unfold
996 # Infinite Promise Sequences
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
997
bb1585bd » briancavalier
2013-02-20 Fix doc links, add doc changes to changelog
998 [when.reduce](#whenreduce), [when/sequence](#whensequence), and [when/pipeline](#whenpipeline) are great ways to process asynchronous arrays of promises and tasks. Sometimes, however, you may not know the array in advance, or may not need or want to process *all* the items in the array. For example, here are a few situations where you may not know the bounds:
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
999
1000 1. You need to process a queue to which items are still being added as you process it
c73e5ab3 » briancavalier
2013-02-12 Almost done with unfold docs
1001 1. You need to execute a task repeatedly until a particular condition becomes true
1002 1. You need to selectively process items in an array, rather than all items
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1003
8bfe7cea » briancavalier
2014-03-17 Update verbage around iterate/unfold
1004 In these cases, you can use `when/iterate` and `when/unfold` to iteratively and asynchronously process items until a particular predicate is true, or even forever without blocking other code.
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1005
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
1006 ## when.iterate
1007
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1008 ```js
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1009 var promise = when.iterate(f, predicate, handler, seed);
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1010 ```
1011
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1012 Generates a potentially infinite stream of promises by repeatedly calling `f` until `predicate` becomes true.
1013
1014 Where:
1015 * `f` - function that, given a seed, returns the next value or a promise for it.
c45bf53a » briancavalier
2014-03-14 Fix a few doc typos, thanks @unscriptable! Use tearDown for PromiseMo…
1016 * `predicate` - function that receives the current iteration value, and should return truthy when the unfold should stop
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1017 * `handler` - function that receives each value as it is produced by `f`. It may return a promise to delay the next iteration.
1018 * `seed` - initial value provided to the first `f` invocation. May be a promise.
1019
1020 ### Examples
1021
1022 Here is a trivial example of counting up to any arbitrary number using promises and delays. Note that this "iteration" is asynchronous and will not block other code. It stores no intermediate arrays in memory, and will never blow the call stack.
1023
1024
1025 ```js
1026 when.iterate(function(x) {
1027 return x+1;
1028 }, function(x) {
1029 // Stop when x >= 100000000000
1030 return x >= 100000000000;
1031 }, function(x) {
1032 console.log(x);
1033 }, 0).done();
1034 ```
1035
1036 Which becomes even nicer with [ES6 arrow functions](http://tc39wiki.calculist.org/es6/arrow-functions/):
1037
1038 ```js
1039 when.iterate(x => x+1, x => x >= 100000000000, x => console.log(x), 0).done();
1040 ```
4e1dc687 » briancavalier
2014-03-10 Start refactoring docs for 3.0
1041
1042 ## when.unfold
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1043
1044 ```js
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1045 var promise = when.unfold(unspool, predicate, handler, seed);
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1046 ```
1047
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1048 Similar to [`when/iterate`](#wheniterate), `when.unfold` generates a potentially infinite stream of promises by repeatedly calling `unspool` until `predicate` becomes true. `when.unfold` allows you to thread additional state information through the iteration.
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1049
c73e5ab3 » briancavalier
2013-02-12 Almost done with unfold docs
1050 Where:
1051 * `unspool` - function that, given a seed, returns a `[valueToSendToHandler, newSeed]` pair. May return an array, array of promises, promise for an array, or promise for an array of promises.
c45bf53a » briancavalier
2014-03-14 Fix a few doc typos, thanks @unscriptable! Use tearDown for PromiseMo…
1052 * `predicate` - function that receives the current seed, and should return truthy when the unfold should stop
c73e5ab3 » briancavalier
2013-02-12 Almost done with unfold docs
1053 * `handler` - function that receives the `valueToSendToHandler` of the current iteration. This function can process `valueToSendToHandler` in whatever way you need. It may return a promise to delay the next iteration of the unfold.
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1054 * `seed` - initial value provided to the first `unspool` invocation. May be a promise.
c73e5ab3 » briancavalier
2013-02-12 Almost done with unfold docs
1055
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1056 ### Examples
1057
e01300b6 » briancavalier
2013-02-13 Finish unfold examples and text
1058 This example generates random numbers at random intervals for 10 seconds.
1059
c45bf53a » briancavalier
2014-03-14 Fix a few doc typos, thanks @unscriptable! Use tearDown for PromiseMo…
1060 The `predicate` could easily be modified (to `return false;`) to generate random numbers *forever*. This would not overflow the call stack, and would not starve application code since it is asynchronous.
e01300b6 » briancavalier
2013-02-13 Finish unfold examples and text
1061
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1062 ```js
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1063 var when = require('when');
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1064
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1065 var end = Date.now() + 10000;
1066 var start = Date.now();
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1067
1068 // Generate random numbers at random intervals!
1069 // Note that we could generate these forever, and never
1070 // blow the call stack, nor would we starve the application
1071 function unspool(seed) {
1072 // seed is passed in, although for this example, we don't need it
1073
1074 // Return a random number as the value, and the time it was generated
1075 // as the new seed
1076 var next = [Math.random(), Date.now()];
1077
1078 // Introduce a delay, just for fun, to show that we can return a promise
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1079 return when(next).delay(Math.random() * 1000);
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1080 }
1081
1082 // Stop after 10 seconds
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1083 function predicate(time) {
1084 return time > end;
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1085 }
1086
1087 function log(value) {
1088 console.log(value);
1089 }
1090
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1091 when.unfold(unspool, predicate, log, start).then(function() {
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1092 console.log('Ran for', Date.now() - start, 'ms');
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1093 }).done();
1094 ```
1095
1096 Which again becomes quite compact with [ES6 arrow functions](http://tc39wiki.calculist.org/es6/arrow-functions/):
1097
1098 ```js
1099 when.unfold(unspool, time => time > end, x => console.log(x), start)
1100 .then(() => console.log('Ran for', Date.now() - start, 'ms'))
1101 .done();
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1102 ```
1103
c45bf53a » briancavalier
2014-03-14 Fix a few doc typos, thanks @unscriptable! Use tearDown for PromiseMo…
1104 This example iterates over files in a directory, mapping each file to the first line (or first 80 characters) of its content. It uses a `predicate` to terminate early, which would not be possible with `when.map`.
e01300b6 » briancavalier
2013-02-13 Finish unfold examples and text
1105
1106 Notice that, while the pair returned by `unspool` is an Array (not a promise), it does *contain* a promise as it's 0th element. The promise will be resolved by the `unfold` machinery.
1107
d23e41b6 » briancavalier
2014-02-13 Close #249. Move when/node/function to when/node. Add when/node/funct…
1108 Notice also the use of `when/node`'s [`call()`](#node-style-asynchronous-functions) to call Node-style async functions (`fs.readdir` and `fs.readFile`), and return a promise instead of requiring a callback. This allows node-style functions can be promisified and composed with other promise-aware functions.
e01300b6 » briancavalier
2013-02-13 Finish unfold examples and text
1109
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1110 ```js
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1111 var when = require('when');
1112 var node = require('when/node');
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1113
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1114 var fs = node.liftAll(require('fs'));
1115
1116 // Lifted fs methods return promises
1117 var files = fs.readdir('.');
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1118
1119 function unspool(files) {
1120 // Return the pair [<*promise* for contents of first file>, <remaining files>]
1121 // the first file's contents will be handed to printFirstLine()
1122 // the remaining files will be handed to condition(), and then
1123 // to the next call to unspool.
1124 // So we are iteratively working our way through the files in
1125 // the dir, but allowing condition() to stop the iteration at
1126 // any point.
1127 var file, content;
1128
1129 file = files[0];
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1130 content = fs.readFile(file)
3c118cb9 » briancavalier
2013-12-02 Update docs with catch/finally aliases
1131 .catch(function(e) {
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1132 return '[Skipping dir ' + file + ']';
1133 });
1134 return [content, files.slice(1)];
1135 }
1136
5e6a7332 » briancavalier
2014-03-17 Merge master to dev
1137 function predicate(remaining) {
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1138 // This could be any test we want. For fun, stop when
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1139 // the next file name starts with a 'p'.
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1140 return remaining[0].charAt(0) === 'p';
1141 }
1142
1143 function printFirstLine(content) {
1144 // Even though contents was a promise in unspool() above,
1145 // when/unfold ensures that it is fully resolved here, i.e. it is
1146 // not a promise any longer.
d23e41b6 » briancavalier
2014-02-13 Close #249. Move when/node/function to when/node. Add when/node/funct…
1147 // We can do any work, even asynchronous work, we need
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1148 // here on the current file
1149
1150 // Node fs returns buffers, convert to string
1151 content = String(content);
1152
1153 // Print the first line, or only the first 80 chars if the fist line is longer
1154 console.log(content.slice(0, Math.min(80, content.indexOf('\n'))));
1155 }
1156
5e6a7332 » briancavalier
2014-03-17 Merge master to dev
1157 when.unfold(unspool, predicate, printFirstLine, files).done();
90ed0abf » briancavalier
2013-02-13 Add unfold example code
1158 ```
c73e5ab3 » briancavalier
2013-02-12 Almost done with unfold docs
1159
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1160 # Task Execution
dcbfb848 » briancavalier
2012-09-25 Adding sequence, pipeline, and parallel docs
1161
ff9412bf » briancavalier
2012-09-25 Doc clarifications. Self-optimizing function for pipeline. Improved u…
1162 These modules allow you to execute tasks in series or parallel. Each module takes an Array of task functions (or a *promise* for an Array), executes the tasks, and returns a promise that resolves when all the tasks have completed.
1163
dcbfb848 » briancavalier
2012-09-25 Adding sequence, pipeline, and parallel docs
1164 ## when/sequence
1165
1166 ```js
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1167 var sequence = require('when/sequence');
ff9412bf » briancavalier
2012-09-25 Doc clarifications. Self-optimizing function for pipeline. Improved u…
1168
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1169 var resultsPromise = sequence(arrayOfTasks, arg1, arg2 /*, ... */);
dcbfb848 » briancavalier
2012-09-25 Adding sequence, pipeline, and parallel docs
1170 ```
1171
1172 Run an array of tasks in sequence, without overlap. Each task will be called with the arguments passed to `when.sequence()`, and each may return a promise or a value.
1173
1174 When all tasks have completed, the returned promise will resolve to an array containing the result of each task at the corresponding array position. The returned promise will reject when any task throws or returns a rejection.
1175
1176 ## when/pipeline
1177
1178 ```js
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1179 var pipeline = require('when/pipeline');
ff9412bf » briancavalier
2012-09-25 Doc clarifications. Self-optimizing function for pipeline. Improved u…
1180
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1181 var resultsPromise = pipeline(arrayOfTasks, arg1, arg2 /*, ... */);
dcbfb848 » briancavalier
2012-09-25 Adding sequence, pipeline, and parallel docs
1182 ```
1183
1184 Run an array of tasks in sequence, without overlap, similarly to [when/sequence](#whensequence). The *first task* (e.g. `arrayOfTasks[0]`) will be called with the arguments passed to `when.pipeline()`, and each subsequence task will be called with the result of the previous task.
1185
1186 Again, each may return a promise or a value. When a task returns a promise, the fully resolved value will be passed to the next task.
1187
1188 When all tasks have completed, the returned promise will resolve to the result of the last task. The returned promise will reject when any task throws or returns a rejection.
1189
1190 ## when/parallel
1191
1192 ```js
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1193 var parallel = require('when/parallel');
ff9412bf » briancavalier
2012-09-25 Doc clarifications. Self-optimizing function for pipeline. Improved u…
1194
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1195 var resultsPromise = parallel(arrayOfTasks, arg1, arg2 /*, ... */);
dcbfb848 » briancavalier
2012-09-25 Adding sequence, pipeline, and parallel docs
1196 ```
1197
dbee625e » briancavalier
2012-09-25 Add info about calling resolve/reject multiple times.
1198 Run an array of tasks in "parallel". The tasks are allowed to execute in any order, and may interleave if they are asynchronous. Each task will be called with the arguments passed to `when.parallel()`, and each may return a promise or a value.
dcbfb848 » briancavalier
2012-09-25 Adding sequence, pipeline, and parallel docs
1199
1200 When all tasks have completed, the returned promise will resolve to an array containing the result of each task at the corresponding array position. The returned promise will reject when any task throws or returns a rejection.
1201
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1202 ## when/poll
1203
1204 ```js
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1205 var poll = require('when/poll');
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1206
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1207 var resultPromise = poll(task, interval, condition /*, initialDelay */);
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1208 ```
1209
1210 Where:
1211
1212 * `work` - function to be called periodically
e01300b6 » briancavalier
2013-02-13 Finish unfold examples and text
1213 * `interval` - interval between calls to `work`. It may be a number *or* a function that returns a promise. If it's a function, the next polling iteration will wait until the promise fulfills.
9e349b1e » briancavalier
2013-02-12 Docs for when/poll. Started docs for unfold
1214 * `condition` - function that evaluates each result of `work`. Polling will continue until it returns a truthy value.
1215 * `initialDelay` - if provided and truthy, the first execution of `work` will be delayed by `interval`. If not provided, or falsey, the first execution of `work` will happen as soon as possible.
1216
1217 Execute a task (`work`) repeatedly at the specified `interval`, until the `condition` function returns true. The `resultPromise` will be resolved with the most recent value returned from `work`. If `work` fails (throws an exception or returns a rejected promise) before `condition` returns true, the `resultPromise` will be rejected.
1218
1219 # Interacting with non-promise code
1c65160e » riccieri
2013-02-10 API docs for when/function
1220
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1221 These modules are aimed at dampening the friction between code that is based on promises and code that follows more conventional approaches to make asynchronous tasks and/or error handling. By using them, you are more likely to be able to reuse code that already exists, while still being able to reap the benefits of promises on your new code.
1c65160e » riccieri
2013-02-10 API docs for when/function
1222
1223 ## Synchronous functions
1224
94391bc7 » briancavalier
2013-03-12 Close #126. Rename bind() to lift(), preserve deprecated bind() alias.
1225 The `when/function` module contains functions for calling and adapting "normal" functions (i.e. those that take plain values, return plain values, and throw exceptions on errors). By calling those functions with `fn.call` and `fn.apply`, or by creating a new function with `fn.lift`, the return value will always be a promise, and thrown exceptions will be turned into rejections. As a bonus, promises given as arguments will be transparently resolved before the call.
1c65160e » riccieri
2013-02-10 API docs for when/function
1226
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1227 ### fn.lift
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1228
1229 ```js
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1230 var promiseFunction = fn.lift(normalFunction);
1231
1232 // Deprecated: using lift to partially apply while lifting
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1233 var promiseFunction = fn.lift(normalFunction, arg1, arg2/* ...more args */);
1234 ```
1235
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1236 When the same function will be called through `fn.call()` or `fn.apply()` multiple times, it can be more efficient to lift it create a wrapper function that has promise-awareness and exposes the same behavior as the original function. That's what `fn.lift()` does: It takes a normal function and returns a new, promise-aware version of it.
1237
1238 Note: Use [`when.lift`](#whenlift) instead: `when.lift` is equivalent to, but also slightly faster than `fn.lift` when used without the (now deprecated) partial application feature.
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1239
1240 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1241 var when = require('when');
1242 var fn = require('when/function');
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1243
1244 function setText(element, text) {
1245 element.text = text;
1246 }
1247
1248 function getMessage() {
1249 // Async function that returns a promise
1250 }
1251
1252 var element = {};
1253
1254 // Resolving the promise ourselves
1255 getMessage().then(function(message) {
1256 setText(element, message);
1257 });
1258
1259 // Using fn.call()
1260 fn.call(setText, element, getMessage());
1261
1262 // Creating a lifted function using fn.lift()
1263 var promiseSetText = fn.lift(setText);
1264 promiseSetText(element, getMessage());
1265
1266 // Partial application
1267 var setElementMessage = fn.lift(setText, element);
1268 setElementMessage(getMessage());
1269 ```
1270
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1271 ### fn.liftAll
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1272
1273 ```js
1274 var liftedApi = fn.liftAll(srcApi);
1275
1276 var liftedApi = fn.liftAll(srcApi, transform);
1277
1278 var destApi = fn.liftAll(srcApi, transform, destApi);
1279 ```
1280
1281 Lifts all the methods of a source object, returning a new object with all the lifted methods. The optional `transform` function allows you to rename or otherwise customize how the lifted functions are added to the returned object. If `destApi` is provided, lifted methods will be added to it, instead of to a new object, and `destApi` will be returned.
1282
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1283 ### fn.call
1c65160e » riccieri
2013-02-10 API docs for when/function
1284
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1285 ```js
1286 var promisedResult = fn.call(normalFunction, arg1, arg2/* ...more args */);
1287 ```
1288
1c65160e » riccieri
2013-02-10 API docs for when/function
1289 A parallel to the `Function.prototype.call` function, that gives promise-awareness to the function given as first argument.
1290
1291 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1292 var when = require('when');
1293 var fn = require('when/function');
1c65160e » riccieri
2013-02-10 API docs for when/function
1294
1295 function divideNumbers(a, b) {
1296 if(b !== 0) {
1297 return a / b;
1298 } else {
1299 throw new Error("Can't divide by zero!");
1300 }
1301 }
1302
1303 // Prints '2'
1304 fn.call(divideNumbers, 10, 5).then(console.log);
1305
1306 // Prints '4'
29abd5fc » briancavalier
2014-05-14 Add promise.fold to TOC, minor cleanup
1307 var promiseForFive = when(5);
1c65160e » riccieri
2013-02-10 API docs for when/function
1308 fn.call(divideNumbers, 20, promiseForFive).then(console.log);
1309
1310 // Prints "Can't divide by zero!"
1311 fn.call(divideNumbers, 10, 0).then(console.log, console.error);
1312 ```
1313
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1314 ### fn.apply
1c65160e » riccieri
2013-02-10 API docs for when/function
1315
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1316 ```js
1317 var promisedResult = fn.apply(normalFunction, [arg1, arg2/* ...more args */]);
1318 ```
1319
1c65160e » riccieri
2013-02-10 API docs for when/function
1320 `fn.apply` is to [`fn.call`](#fncall) as `Function.prototype.apply` is to `Function.prototype.call`: what changes is the way the arguments are taken. While `fn.call` takes the arguments separately, `fn.apply` takes them as an array.
1321
1322 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1323 var when = require('when');
1324 var fn = require('when/function');
1c65160e » riccieri
2013-02-10 API docs for when/function
1325
1326 function sumMultipleNumbers() {
1327 return Array.prototype.reduce.call(arguments, function(prev, n) {
1328 return prev + n;
1329 }, 0);
1330 }
1331
1332 // Prints '50'
1333 fn.apply(sumMultipleNumbers, [10, 20, 20]).then(console.log, console.error);
1334
1335 // Prints 'something wrong happened', and the sum function never executes
1336 var shortCircuit = when.reject("something wrong happened");
1337 fn.apply(sumMultipleNumbers, [10, 20, shortCircuit]).then(console.log, console.error);
1338 ```
1339
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1340 ### fn.compose
94391bc7 » briancavalier
2013-03-12 Close #126. Rename bind() to lift(), preserve deprecated bind() alias.
1341
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1342 ```js
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1343 var composedFunc = fn.compose(func1, func2 /* ...more functions */);
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1344 ```
1345
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1346 Composes multiple functions by piping their return values. It is transparent to whether the functions return 'regular' values or promises: the piped argument is always a resolved value. If one of the functions throws or returns a rejected promise, the promise returned by `composedFunc` will be rejected.
1c65160e » riccieri
2013-02-10 API docs for when/function
1347
1348 ```js
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1349 // Reusing the same functions from the fn.lift() example
1c65160e » riccieri
2013-02-10 API docs for when/function
1350
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1351 // Gets the message from the server every 1s, then sets it on the 'element'
1352 var refreshMessage = fn.compose(getMessage, setElementMessage);
1353 setInterval(refreshMessage, 1000);
1c65160e » riccieri
2013-02-10 API docs for when/function
1354
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1355 // Which is equivalent to:
1356 setInterval(function() {
1357 return fn.call(getMessage).then(setElementMessage);
1358 }, 1000);
1359 ```
1c65160e » riccieri
2013-02-10 API docs for when/function
1360
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1361 # Node-style asynchronous functions
0e125d6b » riccieri
2013-02-10 API docs for node/function
1362
d23e41b6 » briancavalier
2014-02-13 Close #249. Move when/node/function to when/node. Add when/node/funct…
1363 Node.js APIs have their own standard for asynchronous functions: Instead of taking an errback, errors are passed as the first argument to the callback function. To use promises instead of callbacks with node-style asynchronous functions, you can use the `when/node` module, which is very similar to `when/callbacks`, but tuned to this convention.
0e125d6b » riccieri
2013-02-10 API docs for node/function
1364
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1365 Note: There are some Node.js functions that don't follow the typical Node-style async function conventions, such as `http.get`. These functions will not work with `when/node`.
0f9b0314 » gotdibbs
2013-11-11 Clarified usage of node-style function wrappers
1366
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1367 ## node.lift
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1368
1369 ```js
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1370 var promiseFunc = nodefn.lift(nodeStyleFunction);
1371
1372 // Deprecated: using lift to partially apply while lifting
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1373 var promiseFunc = nodefn.lift(nodeStyleFunction, arg1, arg2/*...more args*/);
1374 ```
1375
1376 Function based on the same principles from [`fn.lift()`](#fnlift) and [`callbacks.lift()`](#callbackslift), but tuned to handle nodejs-style async functions.
1377
1378 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1379 var dns = require('dns');
1380 var when = require('when');
1381 var nodefn = require('when/node');
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1382
1383 var resolveAddress = nodefn.lift(dns.resolve);
1384
1385 when.join(
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1386 resolveAddress('twitter.com'),
1387 resolveAddress('facebook.com'),
1388 resolveAddress('google.com')
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1389 ).then(function(addresses) {
1390 // All addresses resolved
1391 }).catch(function(reason) {
1392 // At least one of the lookups failed
1393 });
1394 ```
1395
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1396 ## node.liftAll
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1397
1398 ```js
1399 var liftedApi = fn.liftAll(srcApi);
1400
1401 var liftedApi = fn.liftAll(srcApi, transform);
1402
1403 var destApi = fn.liftAll(srcApi, transform, destApi);
1404 ```
1405
1406 Lifts all the methods of a source object, returning a new object with all the lifted methods. The optional `transform` function allows you to rename or otherwise customize how the lifted functions are added to the returned object. If `destApi` is provided, lifted methods will be added to it, instead of to a new object, and `destApi` will be returned.
1407
1408 ```js
1409 // Lift the entire dns API
456685b8 » briancavalier
2014-03-14 Add more liftAll examples
1410 var dns = require('dns');
1411 var promisedDns = node.liftAll(dns);
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1412
1413 when.join(
456685b8 » briancavalier
2014-03-14 Add more liftAll examples
1414 promisedDns.resolve("twitter.com"),
1415 promisedDns.resolveNs("facebook.com"),
1416 promisedDns.resolveMx("google.com")
88f7e6f4 » briancavalier
2014-03-11 Add liftAll docs. need examples
1417 ).then(function(addresses) {
1418 // All addresses resolved
1419 }).catch(function(reason) {
1420 // At least one of the lookups failed
1421 });
1422 ```
1423
456685b8 » briancavalier
2014-03-14 Add more liftAll examples
1424 For additional flexibility, you can use the optional `transform` function to do things like renaming:
1425
1426 ```js
1427 // Lift all of the fs methods, but name them with an 'Async' suffix
1428 var fs = require('fs');
1429 var promisedFs = node.liftAll(fs, function(promisedFs, liftedFunc, name) {
1430 promisedFs[name + 'Async'] = liftedFunc;
1431 return promisedFs;
1432 });
1433
1434 promisedFs.readFileAsync('file.txt').done(console.log.bind(console));
1435 ```
1436
1437 You can also supply your own destination object onto which all of the lifted functions will be added:
1438
1439 ```js
1440 // Lift all of the fs methods, but name them with an 'Async' suffix
1441 // and add them back onto fs!
1442 var fs = require('fs');
1443 var promisedFs = node.liftAll(fs, function(promisedFs, liftedFunc, name) {
1444 promisedFs[name + 'Async'] = liftedFunc;
1445 return promisedFs;
1446 }, fs);
1447
1448 fs.readFileAsync('file.txt').done(console.log.bind(console));
1449 ```
1450
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1451 ## node.call
0e125d6b » riccieri
2013-02-10 API docs for node/function
1452
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1453 ```js
1454 var promisedResult = nodefn.call(nodeStyleFunction, arg1, arg2/*...more args*/);
1455 ```
1456
6424a4de » riccieri
2013-02-11 Fix internal links
1457 Analogous to [`fn.call()`](#fncall) and [`callbacks.call()`](#callbackscall): Takes a function plus optional arguments to that function, and returns a promise for its final value. The promise will be resolved or rejected depending on whether the conventional error argument is passed or not.
0e125d6b » riccieri
2013-02-10 API docs for node/function
1458
1459 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1460 var fs = require('fs');
9d2c2d51 » Offirmo
2014-03-28 Update api.md
1461 var nodefn = require('when/node');
0e125d6b » riccieri
2013-02-10 API docs for node/function
1462
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1463 var loadPasswd = nodefn.call(fs.readFile, '/etc/passwd');
0e125d6b » riccieri
2013-02-10 API docs for node/function
1464
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1465 loadPasswd.done(function(passwd) {
1466 console.log('Contents of /etc/passwd:\n' + passwd);
0e125d6b » riccieri
2013-02-10 API docs for node/function
1467 }, function(error) {
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1468 console.log('Something wrong happened: ' + error);
0e125d6b » riccieri
2013-02-10 API docs for node/function
1469 });
1470 ```
1471
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1472 ## node.apply
0e125d6b » riccieri
2013-02-10 API docs for node/function
1473
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1474 ```js
5f548a6f » riccieri
2013-02-11 Typo
1475 var promisedResult = nodefn.apply(nodeStyleFunction, [arg1, arg2/*...more args*/]);
aad16852 » riccieri
2013-02-11 Incorporate @briancavalier's suggestions
1476 ```
1477
d23e41b6 » briancavalier
2014-02-13 Close #249. Move when/node/function to when/node. Add when/node/funct…
1478 Following the tradition from `when/function` and `when/callbacks`, `when/node` also provides a array-based alternative to `nodefn.call()`.
0e125d6b » riccieri
2013-02-10 API docs for node/function
1479
1480 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1481 var fs = require('fs');
1482 var nodefn = require('when/node');
0e125d6b » riccieri
2013-02-10 API docs for node/function
1483
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1484 var loadPasswd = nodefn.apply(fs.readFile, ['/etc/passwd']);
0e125d6b » riccieri
2013-02-10 API docs for node/function
1485
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1486 loadPasswd.done(function(passwd) {
1487 console.log('Contents of /etc/passwd:\n' + passwd);
0f9b0314 » gotdibbs
2013-11-11 Clarified usage of node-style function wrappers
1488 }, function(error) {
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1489 console.log('Something wrong happened: ' + error);
0e125d6b » riccieri
2013-02-10 API docs for node/function
1490 });
1491 ```
1492
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1493 ## node.liftCallback
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1494
1495 ```js
1496 var promiseAcceptingFunction = nodefn.liftCallback(nodeback);
1497 ```
1498
1499 Transforms a node-style callback function into a function that accepts a
1500 promise. This allows you to bridge promises and node-style in "the other
1501 direction". For example, if you have a node-style callback,
1502 and a function that returns promises, you can lift the former to allow the
1503 two functions to be composed.
1504
7308e374 » briancavalier
2013-11-06 Update docs for when/node/function bindCallback and liftCallback
1505 The lifted function will always returns its input promise, and always executes
1506 `nodeback` in a future turn of the event loop. Thus, the outcome of `nodeback`
1507 has no bearing on the returned promise.
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1508
7308e374 » briancavalier
2013-11-06 Update docs for when/node/function bindCallback and liftCallback
1509 If `nodeback` throws an exception, it will propagate to the host environment,
1510 just as it would when using node-style callbacks with typical Node.js APIs.
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1511
1512 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1513 var nodefn = require('when/node');
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1514
1515 function fetchData(key) {
1516 // go get the data and,
1517 return promise;
1518 }
1519
1520 function handleData(err, result) {
1521 if(err) {
1522 // handle the error
1523 } else {
1524 // Use the result
1525 }
1526 }
1527
1528 // Lift handleData
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1529 var handlePromisedData = nodefn.liftCallback(handleData);
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1530
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1531 var dataPromise = fetchData(123);
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1532
1533 handlePromisedData(dataPromise);
1534 ```
1535
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1536 ## node.bindCallback
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1537
1538 ```js
235827da » briancavalier
2013-06-19 Fix argument ordering for bindCallback docs
1539 var resultPromise = nodefn.bindCallback(promise, nodeback);
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1540 ```
1541
1542 Lifts and then calls the node-style callback on the provided promise. This is a one-shot version of [nodefn.liftCallback](nodefn-liftcallback), and the `resultPromise` will behave as described there.
1543
1544 ```js
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1545 var nodefn = require('when/node');
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1546
1547 function fetchData(key) {
1548 // go get the data and,
1549 return promise;
1550 }
1551
1552 function handleData(err, result) {
1553 if(err) {
1554 // handle the error
1555 } else {
1556 // Use the result
1557 }
1558 }
1559
1560 // Lift handleData
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1561 var dataPromise = fetchData(123);
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1562
235827da » briancavalier
2013-06-19 Fix argument ordering for bindCallback docs
1563 nodefn.bindCallback(dataPromise, handleData);
a0903d49 » briancavalier
2013-06-18 Add docs for nodefn.liftCallback and nodefn.bindCallback
1564 ```
1565
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1566 ## node.createCallback
1567
1568 ```js
1569 var nodeStyleCallback = nodefn.createCallback(resolver);
1570 ```
1571
1572 A helper function of the `when/node` implementation, which might be useful for cases that aren't covered by the higher level API. It takes an object that responds to the resolver interface (`{ resolve:function, reject:function }`) and returns a function that can be used with any node-style asynchronous function, and will call `resolve()` or `reject()` on the resolver depending on whether the conventional error argument is passed to it.
1573
1574 ```js
1575 var when = require('when');
b184fa3d » dremonkey
2014-05-29 Fixed Typo
1576 var nodefn = require('when/node');
1dff5e19 » briancavalier
2014-03-18 Fix #274. Add missing TOC links, plus other minor api doc cleanup
1577
1578 function nodeStyleAsyncFunction(callback) {
1579 if(Math.random() * 2 > 1) {
1580 callback(new Error('Oh no!'));
1581 } else {
1582 callback(null, "Interesting value");
1583 }
1584 }
1585
1586 var deferred = when.defer();
1587 nodeStyleAsyncFunction(nodefn.createCallback(deferred.resolver));
1588
1589 deferred.promise.then(function(interestingValue) {
1590 console.log(interestingValue)
1591 },function(err) {
1592 console.error(err)
1593 });
1594 ```
1595
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1596 # Asynchronous functions
1597
1598 Much of the asynchronous functionality available to javascript developers, be it directly from the environment or via third party libraries, is callback/errback-based. The `when/callbacks` module provides functions to interact with those APIs via promises in a transparent way, without having to write custom wrappers or change existing code. All the functions on this module (with the exception of `callbacks.promisify()`) assume that the callback and errback will be on the "standard" positions - the penultimate and last arguments, respectively.
1599
1600
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1601 ### callbacks.lift
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1602
1603 ```js
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1604 var promiseFunc = callbacks.lift(callbackTakingFunc);
1605
1606 // Deprecated: using lift to partially apply while lifting
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1607 var promiseFunc = callbacks.lift(callbackTakingFunc, arg1, arg2/* ...more args */);
1608 ```
1609
1610 Much like [`fn.lift()`](#fnlift), `callbacks.lift` creates a promise-friendly function, based on an existing function, but following the asynchronous resolution patters from [`callbacks.call()`](#callbackscall) and [`callbacks.apply()`](#callbacksapply). It can be useful when a particular function needs no be called on multiple places, or for creating an alternative API for a library.
1611
1612 Like `Function.prototype.bind`, additional arguments will be partially applied to the new function.
1613
1614 ```js
1615 // Fictional ajax library, because we don't have enough of those
1616
1617 function traditionalAjax(method, url, callback, errback) {
1618 var xhr = new XMLHttpRequest();
1619 xhr.open(method, url);
1620
1621 xhr.onload = callback;
1622 xhr.onerror = errback;
1623
1624 xhr.send();
1625 }
1626
1627 var myLib = {
1628 // Traditional browser API: Takes callback and errback
1629 ajax: traditionalAjax,
1630
1631 // Promise API: returns a promise, and may take promises as arguments
1632 promiseAjax: callbacks.lift(traditionalAjax)
1633 };
1634 ```
1635
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1636 ### callbacks.liftAll
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1637
1638 ```js
1639 var liftedApi = callbacks.liftAll(srcApi);
1640
1641 var liftedApi = callbacks.liftAll(srcApi, transform);
1642
1643 var destApi = callbacks.liftAll(srcApi, transform, destApi);
1644 ```
1645
1646 Lifts all the methods of a source object, returning a new object with all the lifted methods. The optional `transform` function allows you to rename or otherwise customize how the lifted functions are added to the returned object. If `destApi` is provided, lifted methods will be added to it, instead of to a new object, and `destApi` will be returned.
1647
1648
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1649 ### callbacks.call
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1650
1651 ```js
1652 var promisedResult = callbacks.call(callbackTakingFunc, arg1, arg2/* ...more args */);
1653 ```
1654
1655 Takes a callback-taking function and returns a promise for its final value, forwarding any additional arguments. The promise will be resolved when the function calls its callback, and the resolution value will be callback's first argument. If multiple values are passed to the callback, the promise will resolve to an array. The same thing happens if the function call the errback, with the difference that the promise will be rejected instead.
1656
1657 ```js
1658 var domIsLoaded = callbacks.call($);
1659 domIsLoaded.then(doMyDomStuff);
1660
1661 var waitFiveSeconds = callbacks.call(setTimeout, 5000);
1662 waitFiveSeconds.then(function() {
1663 console.log("Five seconds have passed");
1664 });
1665 ```
1666
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1667 ### callbacks.apply
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1668
1669 ```js
1670 var promisedResult = callbacks.apply(callbackTakingFunc, [arg1, arg2/* ...more args */]);
1671 ```
1672
1673 The array-taking analog to `callbacks.call`, as `Function.prototype.apply` is to `Function.prototype.call`.
1674
1675 ```js
1676 // This example simulates fading away an element, fading in a new one, fetching
1677 // two remote resources, and then waiting for all that to finish before going
1678 // forward. The APIs are all callback-based, but only promises are manipulated.
1679
1680 // Function.prototype.bind is needed to preserve the context
1681 var oldHidden = callbacks.apply($old.fadeOut.bind($old), ["slow"]);
1682
1683 var transitionedScreens = oldHidden.then(function() {
1684 return callbacks.apply($new.fadeIn.bind($new), ["slow"]);
1685 });
1686
1687 var venuesLoaded = callbacks.apply($.getJSON, ["./venues.json"]);
1688 var artistsLoaded = callbacks.apply($.getJSON, ["./artists.json"]);
1689
1690 // Leveraging when.join to combine promises
1691 when.join(venuesLoaded, artistsLoaded, transitionedScreens).then(function() {
1692 // Render next screen when everything is ready
1693 }, function() {
1694 // Catch-all error handler
1695 });
1696 ```
1697
6558022e » briancavalier
2014-03-13 Update docs for when.iterate and unfold. Clean up formatting and "see…
1698 ### callbacks.promisify
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1699
7064d56e » briancavalier
2014-05-14 Add deprecation notices to api docs for when.some and when/callbacks.…
1700 **DEPRECATED**
1701
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1702 ```js
1703 var promiseFunc = callbacks.promisify(nonStandardFunc, {
1704 callback: zeroBasedIndex,
1705 errback: otherZeroBasedIndex,
1706 });
1707 ```
1708
1709 Almost all the functions on the `callbacks` module assume that the creators of the API were kind enough to follow the unspoken standard of taking the callback and errback as the last arguments on the function call; `callbacks.promisify()` is for when they weren't. In addition to the function to be adapted, `promisify` takes an object that describes what are the positions of the callback and errback arguments.
1710
1711 ```js
1712 function inverseStandard(errback, callback) {
1713 // ...
1714 }
1715
1716 var promisified1 = callbacks.promisify(inverseStandard, {
1717 callback: 1,
1718 errback: 0, // indexes are zero-based
1719 });
1720
1721 function firstAndThird(callback, someParam, errback) {
1722 // ...
1723 }
1724
1725 var promisified2 = callbacks.promisify(firstAndThird, {
1726 callback: 0,
1727 errback: 2,
1728 });
1729
1730 // The arguments to the promisified call are interleaved with the callback and
1731 // errback.
1732 promisified(10);
1733
1734 function inverseVariadic(/* arg1, arg2, arg3... , */errback, callback) {
1735 // ...
1736 }
1737
1738 var promisified3 = callbacks.promisify(inverseVariadic, {
1739 callback: -1, // Negative indexes represent positions relative to the end
1740 errback: -2,
1741 });
1742 ```
1743
4912ec93 » briancavalier
2014-01-23 Start generator docs
1744 # ES6 generators
1745
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1746 **Experimental**: Requires an environment that supports ES6 generators and the `yield` keyword.
1747
4912ec93 » briancavalier
2014-01-23 Start generator docs
1748 ## when/generator
1749
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1750 The `when/generator` module provides APIs for using ES6 generators as coroutines. You can `yield` promises to await their resolution while control is transferred back to the JS event loop. You can write code that looks and acts like synchronous code, even using synchronous `try`, `catch` and `finally`.
1751
1752 The following example uses `generator.call` to fetch a list of todos for a user, `yield`ing control until the promise returned by `getTodosForUser` is resolved. If the promise fulfills, execution will continue and show the todos. If the promise rejects, the rejection will be translated to a synchronous exception (using ES6 generator `.throw()`). As you'd expect, control will jump to the `catch` and show an error.
1753
1754 ```js
1755 var gen = require('when/generator');
1756
1757 gen.call(function*(todosFilter, userId) {
1758 var todos;
1759 try {
1760 todos = yield getTodosForUser(userId);
1761 showTodos(todos.filter(todosFilter));
1762 } catch(e) {
1763 showError(e);
1764 }
1765 }, isRecentTodo, 123);
1766
1767 function getTodosForUser(userId) {
1768 // returns a promise for an array of the user's todos
1769 }
1770
1771 ```
1772
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1773 ## generator.lift
4912ec93 » briancavalier
2014-01-23 Start generator docs
1774 ```js
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1775 var coroutine = generator.lift(es6generator*);
1776
1777 // Deprecated: using lift to partially apply while lifting
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1778 var coroutine = generator.lift(es6generator*, arg1, arg2/*...more args*/);
4912ec93 » briancavalier
2014-01-23 Start generator docs
1779 ```
1780
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1781 Lifts `es6generator` to a promise-aware coroutine, instead of calling it immediately. Returns a function that, when called, can use `yield` to await promises. This can be more convenient than using `generator.call` or `generator.apply` by allowing you to create the coroutine once, and call it repeatedly as a plain function.
1782
1783 Additional arguments provided to `generator.lift` will be partially applied to the lifted coroutine.
1784
1785 Here is a revised version of the above example using `generator.lift`. Note that we're also partially applying the `isRecentTodos` filtering function.
1786
1787 ```js
1788 var gen = require('when/generator');
1789
1790 // Use generator.lift to create a function that acts as a coroutine
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1791 var getRecentTodosForUser = gen.lift(function*(userId) {
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1792 var todos;
1793 try {
1794 todos = yield getTodosForUser(userId);
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1795 showTodos(todos.filter(isRecentTodo));
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1796 } catch(e) {
1797 showError(e);
1798 }
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1799 });
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1800
1801 function getTodosForUser(userId) {
1802 // returns a promise for an array of the user's todos
1803 }
1804
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1805 // Get the recent todos for user 123.
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1806 getRecentTodosForUser(123);
1807 ```
1808
1809 In addition to `try`, `catch`, and `finally`, `return` also works as expected. In this revised example, `yield` allows us to return a result and move error handling out to the caller.
1810
1811 ```js
1812 var gen = require('when/generator');
1813
1814 // Use generator.lift to create a function that acts as a coroutine
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1815 var getRecentTodosForUser = gen.lift(function*(userId) {
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1816 var todos = yield getTodosForUser(userId);
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1817 return todos.filter(isRecentTodo);
1818 });
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1819
1820 function getTodosForUser(userId) {
1821 // returns a promise for an array of the user's todos
1822 }
1823
13b91c22 » briancavalier
2014-05-08 Update changelog and API docs for upcoming 3.2.0
1824 // Get the recent todos for user 123
925741f5 » briancavalier
2014-01-27 Add when/generator docs
1825 var filteredTodos = getRecentTodosForUser(123);
1826 ```
4912ec93 » briancavalier
2014-01-23 Start generator docs
1827
0174a126 » briancavalier
2014-03-12 Add when/poll link to TOC. Reorder a bit
1828 ## generator.call
1829
1830 ```js
1831 var resultPromise = generator.call(es6generator*, arg1, arg2/*...more args*/);
1832 ```
1833
1834 Immediately calls `es6generator` with the supplied args, and allows it use `yield` to await promises.
1835
1836 ## generator.apply
1837
1838 ```js
1839 var resultPromise = generator.apply(es6generator*, [arg1, arg2/*...more args*/]);
1840 ```
1841
1842 Similar to `generator.call`, immediately calls `es6generator` with the supplied args array, and allows it use `yield` to await promises.
1843
1844 # Limiting Concurrency
1845
1846 ## when/guard
1847
1848 ```js
1849 var guard = require('when/guard');
1850
1851 var guarded = guard(condition, function() {
1852 // .. Do important stuff
1853 });
1854 ```
1855
1856 Where:
1857
1858 * `condition` is a concurrency limiting condition, such as [guard.n](#guardn)
1859