1 | [](http://travis-ci.org/kriskowal/q) |
---|
2 | |
---|
3 | <a href="http://promises-aplus.github.com/promises-spec"> |
---|
4 | <img src="http://promises-aplus.github.com/promises-spec/assets/logo-small.png" |
---|
5 | align="right" alt="Promises/A+ logo" /> |
---|
6 | </a> |
---|
7 | |
---|
8 | If a function cannot return a value or throw an exception without |
---|
9 | blocking, it can return a promise instead. A promise is an object |
---|
10 | that represents the return value or the thrown exception that the |
---|
11 | function may eventually provide. A promise can also be used as a |
---|
12 | proxy for a [remote object][Q-Connection] to overcome latency. |
---|
13 | |
---|
14 | [Q-Connection]: https://github.com/kriskowal/q-connection |
---|
15 | |
---|
16 | On the first pass, promises can mitigate the â[Pyramid of |
---|
17 | Doom][POD]â: the situation where code marches to the right faster |
---|
18 | than it marches forward. |
---|
19 | |
---|
20 | [POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ |
---|
21 | |
---|
22 | ```javascript |
---|
23 | step1(function (value1) { |
---|
24 | step2(value1, function(value2) { |
---|
25 | step3(value2, function(value3) { |
---|
26 | step4(value3, function(value4) { |
---|
27 | // Do something with value4 |
---|
28 | }); |
---|
29 | }); |
---|
30 | }); |
---|
31 | }); |
---|
32 | ``` |
---|
33 | |
---|
34 | With a promise library, you can flatten the pyramid. |
---|
35 | |
---|
36 | ```javascript |
---|
37 | Q.fcall(step1) |
---|
38 | .then(step2) |
---|
39 | .then(step3) |
---|
40 | .then(step4) |
---|
41 | .then(function (value4) { |
---|
42 | // Do something with value4 |
---|
43 | }, function (error) { |
---|
44 | // Handle any error from step1 through step4 |
---|
45 | }) |
---|
46 | .done(); |
---|
47 | ``` |
---|
48 | |
---|
49 | With this approach, you also get implicit error propagation, |
---|
50 | just like ``try``, ``catch``, and ``finally``. An error in |
---|
51 | ``step1`` will flow all the way to ``step5``, where itâs |
---|
52 | caught and handled. |
---|
53 | |
---|
54 | The callback approach is called an âinversion of controlâ. |
---|
55 | A function that accepts a callback instead of a return value |
---|
56 | is saying, âDonât call me, Iâll call you.â. Promises |
---|
57 | [un-invert][IOC] the inversion, cleanly separating the input |
---|
58 | arguments from control flow arguments. This simplifies the |
---|
59 | use and creation of APIâs, particularly variadic, |
---|
60 | rest and spread arguments. |
---|
61 | |
---|
62 | [IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript |
---|
63 | |
---|
64 | |
---|
65 | ## Getting Started |
---|
66 | |
---|
67 | The Q module can be loaded as: |
---|
68 | |
---|
69 | - A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and |
---|
70 | gzipped. |
---|
71 | - A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as |
---|
72 | the [q](https://npmjs.org/package/q) package |
---|
73 | - An AMD module |
---|
74 | - A [component](https://github.com/component/component) as ``microjs/q`` |
---|
75 | - Using [bower](http://bower.io/) as ``q`` |
---|
76 | - Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q) |
---|
77 | |
---|
78 | Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more. |
---|
79 | Additionally, there are many libraries that produce and consume Q promises for |
---|
80 | everything from file system/database access or RPC to templating. For a list of |
---|
81 | some of the more popular ones, see [Libraries][]. |
---|
82 | |
---|
83 | Please join the Q-Continuum [mailing list](https://groups.google.com/forum/#!forum/q-continuum). |
---|
84 | |
---|
85 | [Libraries]: https://github.com/kriskowal/q/wiki/Libraries |
---|
86 | |
---|
87 | |
---|
88 | ## Tutorial |
---|
89 | |
---|
90 | Promises have a ``then`` method, which you can use to get the eventual |
---|
91 | return value (fulfillment) or thrown exception (rejection). |
---|
92 | |
---|
93 | ```javascript |
---|
94 | promiseMeSomething() |
---|
95 | .then(function (value) { |
---|
96 | }, function (reason) { |
---|
97 | }); |
---|
98 | ``` |
---|
99 | |
---|
100 | If ``promiseMeSomething`` returns a promise that gets fulfilled later |
---|
101 | with a return value, the first function (the fulfillment handler) will be |
---|
102 | called with the value. However, if the ``promiseMeSomething`` function |
---|
103 | gets rejected later by a thrown exception, the second function (the |
---|
104 | rejection handler) will be called with the exception. |
---|
105 | |
---|
106 | Note that resolution of a promise is always asynchronous: that is, the |
---|
107 | fulfillment or rejection handler will always be called in the next turn of the |
---|
108 | event loop (i.e. `process.nextTick` in Node). This gives you a nice |
---|
109 | guarantee when mentally tracing the flow of your code, namely that |
---|
110 | ``then`` will always return before either handler is executed. |
---|
111 | |
---|
112 | |
---|
113 | ### Propagation |
---|
114 | |
---|
115 | The ``then`` method returns a promise, which in this example, Iâm |
---|
116 | assigning to ``outputPromise``. |
---|
117 | |
---|
118 | ```javascript |
---|
119 | var outputPromise = getInputPromise() |
---|
120 | .then(function (input) { |
---|
121 | }, function (reason) { |
---|
122 | }); |
---|
123 | ``` |
---|
124 | |
---|
125 | The ``outputPromise`` variable becomes a new promise for the return |
---|
126 | value of either handler. Since a function can only either return a |
---|
127 | value or throw an exception, only one handler will ever be called and it |
---|
128 | will be responsible for resolving ``outputPromise``. |
---|
129 | |
---|
130 | - If you return a value in a handler, ``outputPromise`` will get |
---|
131 | fulfilled. |
---|
132 | |
---|
133 | - If you throw an exception in a handler, ``outputPromise`` will get |
---|
134 | rejected. |
---|
135 | |
---|
136 | - If you return a **promise** in a handler, ``outputPromise`` will |
---|
137 | âbecomeâ that promise. Being able to become a new promise is useful |
---|
138 | for managing delays, combining results, or recovering from errors. |
---|
139 | |
---|
140 | If the ``getInputPromise()`` promise gets rejected and you omit the |
---|
141 | rejection handler, the **error** will go to ``outputPromise``: |
---|
142 | |
---|
143 | ```javascript |
---|
144 | var outputPromise = getInputPromise() |
---|
145 | .then(function (value) { |
---|
146 | }); |
---|
147 | ``` |
---|
148 | |
---|
149 | If the input promise gets fulfilled and you omit the fulfillment handler, the |
---|
150 | **value** will go to ``outputPromise``: |
---|
151 | |
---|
152 | ```javascript |
---|
153 | var outputPromise = getInputPromise() |
---|
154 | .then(null, function (error) { |
---|
155 | }); |
---|
156 | ``` |
---|
157 | |
---|
158 | Q promises provide a ``fail`` shorthand for ``then`` when you are only |
---|
159 | interested in handling the error: |
---|
160 | |
---|
161 | ```javascript |
---|
162 | var outputPromise = getInputPromise() |
---|
163 | .fail(function (error) { |
---|
164 | }); |
---|
165 | ``` |
---|
166 | |
---|
167 | If you are writing JavaScript for modern engines only or using |
---|
168 | CoffeeScript, you may use `catch` instead of `fail`. |
---|
169 | |
---|
170 | Promises also have a ``fin`` function that is like a ``finally`` clause. |
---|
171 | The final handler gets called, with no arguments, when the promise |
---|
172 | returned by ``getInputPromise()`` either returns a value or throws an |
---|
173 | error. The value returned or error thrown by ``getInputPromise()`` |
---|
174 | passes directly to ``outputPromise`` unless the final handler fails, and |
---|
175 | may be delayed if the final handler returns a promise. |
---|
176 | |
---|
177 | ```javascript |
---|
178 | var outputPromise = getInputPromise() |
---|
179 | .fin(function () { |
---|
180 | // close files, database connections, stop servers, conclude tests |
---|
181 | }); |
---|
182 | ``` |
---|
183 | |
---|
184 | - If the handler returns a value, the value is ignored |
---|
185 | - If the handler throws an error, the error passes to ``outputPromise`` |
---|
186 | - If the handler returns a promise, ``outputPromise`` gets postponed. The |
---|
187 | eventual value or error has the same effect as an immediate return |
---|
188 | value or thrown error: a value would be ignored, an error would be |
---|
189 | forwarded. |
---|
190 | |
---|
191 | If you are writing JavaScript for modern engines only or using |
---|
192 | CoffeeScript, you may use `finally` instead of `fin`. |
---|
193 | |
---|
194 | ### Chaining |
---|
195 | |
---|
196 | There are two ways to chain promises. You can chain promises either |
---|
197 | inside or outside handlers. The next two examples are equivalent. |
---|
198 | |
---|
199 | ```javascript |
---|
200 | return getUsername() |
---|
201 | .then(function (username) { |
---|
202 | return getUser(username) |
---|
203 | .then(function (user) { |
---|
204 | // if we get here without an error, |
---|
205 | // the value returned here |
---|
206 | // or the exception thrown here |
---|
207 | // resolves the promise returned |
---|
208 | // by the first line |
---|
209 | }) |
---|
210 | }); |
---|
211 | ``` |
---|
212 | |
---|
213 | ```javascript |
---|
214 | return getUsername() |
---|
215 | .then(function (username) { |
---|
216 | return getUser(username); |
---|
217 | }) |
---|
218 | .then(function (user) { |
---|
219 | // if we get here without an error, |
---|
220 | // the value returned here |
---|
221 | // or the exception thrown here |
---|
222 | // resolves the promise returned |
---|
223 | // by the first line |
---|
224 | }); |
---|
225 | ``` |
---|
226 | |
---|
227 | The only difference is nesting. Itâs useful to nest handlers if you |
---|
228 | need to capture multiple input values in your closure. |
---|
229 | |
---|
230 | ```javascript |
---|
231 | function authenticate() { |
---|
232 | return getUsername() |
---|
233 | .then(function (username) { |
---|
234 | return getUser(username); |
---|
235 | }) |
---|
236 | // chained because we will not need the user name in the next event |
---|
237 | .then(function (user) { |
---|
238 | return getPassword() |
---|
239 | // nested because we need both user and password next |
---|
240 | .then(function (password) { |
---|
241 | if (user.passwordHash !== hash(password)) { |
---|
242 | throw new Error("Can't authenticate"); |
---|
243 | } |
---|
244 | }); |
---|
245 | }); |
---|
246 | } |
---|
247 | ``` |
---|
248 | |
---|
249 | |
---|
250 | ### Combination |
---|
251 | |
---|
252 | You can turn an array of promises into a promise for the whole, |
---|
253 | fulfilled array using ``all``. |
---|
254 | |
---|
255 | ```javascript |
---|
256 | return Q.all([ |
---|
257 | eventualAdd(2, 2), |
---|
258 | eventualAdd(10, 20) |
---|
259 | ]); |
---|
260 | ``` |
---|
261 | |
---|
262 | If you have a promise for an array, you can use ``spread`` as a |
---|
263 | replacement for ``then``. The ``spread`` function âspreadsâ the |
---|
264 | values over the arguments of the fulfillment handler. The rejection handler |
---|
265 | will get called at the first sign of failure. That is, whichever of |
---|
266 | the recived promises fails first gets handled by the rejection handler. |
---|
267 | |
---|
268 | ```javascript |
---|
269 | function eventualAdd(a, b) { |
---|
270 | return Q.spread([a, b], function (a, b) { |
---|
271 | return a + b; |
---|
272 | }) |
---|
273 | } |
---|
274 | ``` |
---|
275 | |
---|
276 | But ``spread`` calls ``all`` initially, so you can skip it in chains. |
---|
277 | |
---|
278 | ```javascript |
---|
279 | return getUsername() |
---|
280 | .then(function (username) { |
---|
281 | return [username, getUser(username)]; |
---|
282 | }) |
---|
283 | .spread(function (username, user) { |
---|
284 | }); |
---|
285 | ``` |
---|
286 | |
---|
287 | The ``all`` function returns a promise for an array of values. When this |
---|
288 | promise is fulfilled, the array contains the fulfillment values of the original |
---|
289 | promises, in the same order as those promises. If one of the given promises |
---|
290 | is rejected, the returned promise is immediately rejected, not waiting for the |
---|
291 | rest of the batch. If you want to wait for all of the promises to either be |
---|
292 | fulfilled or rejected, you can use ``allSettled``. |
---|
293 | |
---|
294 | ```javascript |
---|
295 | Q.allSettled(promises) |
---|
296 | .then(function (results) { |
---|
297 | results.forEach(function (result) { |
---|
298 | if (result.state === "fulfilled") { |
---|
299 | var value = result.value; |
---|
300 | } else { |
---|
301 | var reason = result.reason; |
---|
302 | } |
---|
303 | }); |
---|
304 | }); |
---|
305 | ``` |
---|
306 | |
---|
307 | |
---|
308 | ### Sequences |
---|
309 | |
---|
310 | If you have a number of promise-producing functions that need |
---|
311 | to be run sequentially, you can of course do so manually: |
---|
312 | |
---|
313 | ```javascript |
---|
314 | return foo(initialVal).then(bar).then(baz).then(qux); |
---|
315 | ``` |
---|
316 | |
---|
317 | However, if you want to run a dynamically constructed sequence of |
---|
318 | functions, you'll want something like this: |
---|
319 | |
---|
320 | ```javascript |
---|
321 | var funcs = [foo, bar, baz, qux]; |
---|
322 | |
---|
323 | var result = Q.resolve(initialVal); |
---|
324 | funcs.forEach(function (f) { |
---|
325 | result = result.then(f); |
---|
326 | }); |
---|
327 | return result; |
---|
328 | ``` |
---|
329 | |
---|
330 | You can make this slightly more compact using `reduce`: |
---|
331 | |
---|
332 | ```javascript |
---|
333 | return funcs.reduce(function (soFar, f) { |
---|
334 | return soFar.then(f); |
---|
335 | }, Q.resolve(initialVal)); |
---|
336 | ``` |
---|
337 | |
---|
338 | Or, you could use th ultra-compact version: |
---|
339 | |
---|
340 | ```javascript |
---|
341 | return funcs.reduce(Q.when, Q()); |
---|
342 | ``` |
---|
343 | |
---|
344 | ### Handling Errors |
---|
345 | |
---|
346 | One sometimes-unintuive aspect of promises is that if you throw an |
---|
347 | exception in the fulfillment handler, it will not be be caught by the error |
---|
348 | handler. |
---|
349 | |
---|
350 | ```javascript |
---|
351 | return foo() |
---|
352 | .then(function (value) { |
---|
353 | throw new Error("Can't bar."); |
---|
354 | }, function (error) { |
---|
355 | // We only get here if "foo" fails |
---|
356 | }); |
---|
357 | ``` |
---|
358 | |
---|
359 | To see why this is, consider the parallel between promises and |
---|
360 | ``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error |
---|
361 | handler represents a ``catch`` for ``foo()``, while the fulfillment handler |
---|
362 | represents code that happens *after* the ``try``/``catch`` block. |
---|
363 | That code then needs its own ``try``/``catch`` block. |
---|
364 | |
---|
365 | In terms of promises, this means chaining your rejection handler: |
---|
366 | |
---|
367 | ```javascript |
---|
368 | return foo() |
---|
369 | .then(function (value) { |
---|
370 | throw new Error("Can't bar."); |
---|
371 | }) |
---|
372 | .fail(function (error) { |
---|
373 | // We get here with either foo's error or bar's error |
---|
374 | }); |
---|
375 | ``` |
---|
376 | |
---|
377 | ### Progress Notification |
---|
378 | |
---|
379 | It's possible for promises to report their progress, e.g. for tasks that take a |
---|
380 | long time like a file upload. Not all promises will implement progress |
---|
381 | notifications, but for those that do, you can consume the progress values using |
---|
382 | a third parameter to ``then``: |
---|
383 | |
---|
384 | ```javascript |
---|
385 | return uploadFile() |
---|
386 | .then(function () { |
---|
387 | // Success uploading the file |
---|
388 | }, function (err) { |
---|
389 | // There was an error, and we get the reason for error |
---|
390 | }, function (progress) { |
---|
391 | // We get notified of the upload's progress as it is executed |
---|
392 | }); |
---|
393 | ``` |
---|
394 | |
---|
395 | Like `fail`, Q also provides a shorthand for progress callbacks |
---|
396 | called `progress`: |
---|
397 | |
---|
398 | ```javascript |
---|
399 | return uploadFile().progress(function (progress) { |
---|
400 | // We get notified of the upload's progress |
---|
401 | }); |
---|
402 | ``` |
---|
403 | |
---|
404 | ### The End |
---|
405 | |
---|
406 | When you get to the end of a chain of promises, you should either |
---|
407 | return the last promise or end the chain. Since handlers catch |
---|
408 | errors, itâs an unfortunate pattern that the exceptions can go |
---|
409 | unobserved. |
---|
410 | |
---|
411 | So, either return it, |
---|
412 | |
---|
413 | ```javascript |
---|
414 | return foo() |
---|
415 | .then(function () { |
---|
416 | return "bar"; |
---|
417 | }); |
---|
418 | ``` |
---|
419 | |
---|
420 | Or, end it. |
---|
421 | |
---|
422 | ```javascript |
---|
423 | foo() |
---|
424 | .then(function () { |
---|
425 | return "bar"; |
---|
426 | }) |
---|
427 | .done(); |
---|
428 | ``` |
---|
429 | |
---|
430 | Ending a promise chain makes sure that, if an error doesnât get |
---|
431 | handled before the end, it will get rethrown and reported. |
---|
432 | |
---|
433 | This is a stopgap. We are exploring ways to make unhandled errors |
---|
434 | visible without any explicit handling. |
---|
435 | |
---|
436 | |
---|
437 | ### The Beginning |
---|
438 | |
---|
439 | Everything above assumes you get a promise from somewhere else. This |
---|
440 | is the common case. Every once in a while, you will need to create a |
---|
441 | promise from scratch. |
---|
442 | |
---|
443 | #### Using ``Q.fcall`` |
---|
444 | |
---|
445 | You can create a promise from a value using ``Q.fcall``. This returns a |
---|
446 | promise for 10. |
---|
447 | |
---|
448 | ```javascript |
---|
449 | return Q.fcall(function () { |
---|
450 | return 10; |
---|
451 | }); |
---|
452 | ``` |
---|
453 | |
---|
454 | You can also use ``fcall`` to get a promise for an exception. |
---|
455 | |
---|
456 | ```javascript |
---|
457 | return Q.fcall(function () { |
---|
458 | throw new Error("Can't do it"); |
---|
459 | }); |
---|
460 | ``` |
---|
461 | |
---|
462 | As the name implies, ``fcall`` can call functions, or even promised |
---|
463 | functions. This uses the ``eventualAdd`` function above to add two |
---|
464 | numbers. |
---|
465 | |
---|
466 | ```javascript |
---|
467 | return Q.fcall(eventualAdd, 2, 2); |
---|
468 | ``` |
---|
469 | |
---|
470 | |
---|
471 | #### Using Deferreds |
---|
472 | |
---|
473 | If you have to interface with asynchronous functions that are callback-based |
---|
474 | instead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and |
---|
475 | friends). But much of the time, the solution will be to use *deferreds*. |
---|
476 | |
---|
477 | ```javascript |
---|
478 | var deferred = Q.defer(); |
---|
479 | FS.readFile("foo.txt", "utf-8", function (error, text) { |
---|
480 | if (error) { |
---|
481 | deferred.reject(new Error(error)); |
---|
482 | } else { |
---|
483 | deferred.resolve(text); |
---|
484 | } |
---|
485 | }); |
---|
486 | return deferred.promise; |
---|
487 | ``` |
---|
488 | |
---|
489 | Note that a deferred can be resolved with a value or a promise. The |
---|
490 | ``reject`` function is a shorthand for resolving with a rejected |
---|
491 | promise. |
---|
492 | |
---|
493 | ```javascript |
---|
494 | // this: |
---|
495 | deferred.reject(new Error("Can't do it")); |
---|
496 | |
---|
497 | // is shorthand for: |
---|
498 | var rejection = Q.fcall(function () { |
---|
499 | throw new Error("Can't do it"); |
---|
500 | }); |
---|
501 | deferred.resolve(rejection); |
---|
502 | ``` |
---|
503 | |
---|
504 | This is a simplified implementation of ``Q.delay``. |
---|
505 | |
---|
506 | ```javascript |
---|
507 | function delay(ms) { |
---|
508 | var deferred = Q.defer(); |
---|
509 | setTimeout(deferred.resolve, ms); |
---|
510 | return deferred.promise; |
---|
511 | } |
---|
512 | ``` |
---|
513 | |
---|
514 | This is a simplified implementation of ``Q.timeout`` |
---|
515 | |
---|
516 | ```javascript |
---|
517 | function timeout(promise, ms) { |
---|
518 | var deferred = Q.defer(); |
---|
519 | Q.when(promise, deferred.resolve); |
---|
520 | Q.when(delay(ms), function () { |
---|
521 | deferred.reject(new Error("Timed out")); |
---|
522 | }); |
---|
523 | return deferred.promise; |
---|
524 | } |
---|
525 | ``` |
---|
526 | |
---|
527 | Finally, you can send a progress notification to the promise with |
---|
528 | ``deferred.notify``. |
---|
529 | |
---|
530 | For illustration, this is a wrapper for XML HTTP requests in the browser. Note |
---|
531 | that a more [thorough][XHR] implementation would be in order in practice. |
---|
532 | |
---|
533 | [XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73 |
---|
534 | |
---|
535 | ```javascript |
---|
536 | function requestOkText(url) { |
---|
537 | var request = new XMLHttpRequest(); |
---|
538 | var deferred = Q.defer(); |
---|
539 | |
---|
540 | request.open("GET", url, true); |
---|
541 | request.onload = onload; |
---|
542 | request.onerror = onerror; |
---|
543 | request.onprogress = onprogress; |
---|
544 | request.send(); |
---|
545 | |
---|
546 | function onload() { |
---|
547 | if (request.status === 200) { |
---|
548 | deferred.resolve(request.responseText); |
---|
549 | } else { |
---|
550 | deferred.reject(new Error("Status code was " + request.status)); |
---|
551 | } |
---|
552 | } |
---|
553 | |
---|
554 | function onerror() { |
---|
555 | deferred.reject(new Error("Can't XHR " + JSON.stringify(url))); |
---|
556 | } |
---|
557 | |
---|
558 | function onprogress(event) { |
---|
559 | deferred.notify(event.loaded / event.total); |
---|
560 | } |
---|
561 | |
---|
562 | return deferred.promise; |
---|
563 | } |
---|
564 | ``` |
---|
565 | |
---|
566 | Below is an example of how to use this ``requestOkText`` function: |
---|
567 | |
---|
568 | ```javascript |
---|
569 | requestOkText("http://localhost:3000") |
---|
570 | .then(function (responseText) { |
---|
571 | // If the HTTP response returns 200 OK, log the response text. |
---|
572 | console.log(responseText); |
---|
573 | }, function (error) { |
---|
574 | // If there's an error or a non-200 status code, log the error. |
---|
575 | console.error(error); |
---|
576 | }, function (progress) { |
---|
577 | // Log the progress as it comes in. |
---|
578 | console.log("Request progress: " + Math.round(progress * 100) + "%"); |
---|
579 | }); |
---|
580 | ``` |
---|
581 | |
---|
582 | ### The Middle |
---|
583 | |
---|
584 | If you are using a function that may return a promise, but just might |
---|
585 | return a value if it doesnât need to defer, you can use the âstaticâ |
---|
586 | methods of the Q library. |
---|
587 | |
---|
588 | The ``when`` function is the static equivalent for ``then``. |
---|
589 | |
---|
590 | ```javascript |
---|
591 | return Q.when(valueOrPromise, function (value) { |
---|
592 | }, function (error) { |
---|
593 | }); |
---|
594 | ``` |
---|
595 | |
---|
596 | All of the other methods on a promise have static analogs with the |
---|
597 | same name. |
---|
598 | |
---|
599 | The following are equivalent: |
---|
600 | |
---|
601 | ```javascript |
---|
602 | return Q.all([a, b]); |
---|
603 | ``` |
---|
604 | |
---|
605 | ```javascript |
---|
606 | return Q.fcall(function () { |
---|
607 | return [a, b]; |
---|
608 | }) |
---|
609 | .all(); |
---|
610 | ``` |
---|
611 | |
---|
612 | When working with promises provided by other libraries, you should |
---|
613 | convert it to a Q promise. Not all promise libraries make the same |
---|
614 | guarantees as Q and certainly donât provide all of the same methods. |
---|
615 | Most libraries only provide a partially functional ``then`` method. |
---|
616 | This thankfully is all we need to turn them into vibrant Q promises. |
---|
617 | |
---|
618 | ```javascript |
---|
619 | return Q.when($.ajax(...)) |
---|
620 | .then(function () { |
---|
621 | }); |
---|
622 | ``` |
---|
623 | |
---|
624 | If there is any chance that the promise you receive is not a Q promise |
---|
625 | as provided by your library, you should wrap it using a Q function. |
---|
626 | You can even use ``Q.invoke`` as a shorthand. |
---|
627 | |
---|
628 | ```javascript |
---|
629 | return Q.invoke($, 'ajax', ...) |
---|
630 | .then(function () { |
---|
631 | }); |
---|
632 | ``` |
---|
633 | |
---|
634 | |
---|
635 | ### Over the Wire |
---|
636 | |
---|
637 | A promise can serve as a proxy for another object, even a remote |
---|
638 | object. There are methods that allow you to optimistically manipulate |
---|
639 | properties or call functions. All of these interactions return |
---|
640 | promises, so they can be chained. |
---|
641 | |
---|
642 | ``` |
---|
643 | direct manipulation using a promise as a proxy |
---|
644 | -------------------------- ------------------------------- |
---|
645 | value.foo promise.get("foo") |
---|
646 | value.foo = value promise.put("foo", value) |
---|
647 | delete value.foo promise.del("foo") |
---|
648 | value.foo(...args) promise.post("foo", [args]) |
---|
649 | value.foo(...args) promise.invoke("foo", ...args) |
---|
650 | value(...args) promise.fapply([args]) |
---|
651 | value(...args) promise.fcall(...args) |
---|
652 | ``` |
---|
653 | |
---|
654 | If the promise is a proxy for a remote object, you can shave |
---|
655 | round-trips by using these functions instead of ``then``. To take |
---|
656 | advantage of promises for remote objects, check out [Q-Connection][]. |
---|
657 | |
---|
658 | [Q-Connection]: https://github.com/kriskowal/q-connection |
---|
659 | |
---|
660 | Even in the case of non-remote objects, these methods can be used as |
---|
661 | shorthand for particularly-simple fulfillment handlers. For example, you |
---|
662 | can replace |
---|
663 | |
---|
664 | ```javascript |
---|
665 | return Q.fcall(function () { |
---|
666 | return [{ foo: "bar" }, { foo: "baz" }]; |
---|
667 | }) |
---|
668 | .then(function (value) { |
---|
669 | return value[0].foo; |
---|
670 | }); |
---|
671 | ``` |
---|
672 | |
---|
673 | with |
---|
674 | |
---|
675 | ```javascript |
---|
676 | return Q.fcall(function () { |
---|
677 | return [{ foo: "bar" }, { foo: "baz" }]; |
---|
678 | }) |
---|
679 | .get(0) |
---|
680 | .get("foo"); |
---|
681 | ``` |
---|
682 | |
---|
683 | |
---|
684 | ### Adapting Node |
---|
685 | |
---|
686 | If you're working with functions that make use of the Node.js callback pattern, |
---|
687 | Q provides a few useful utility functions for converting between them. The |
---|
688 | most straightforward are probably `Q.nfcall` and `Q.nfapply` ("Node function |
---|
689 | call/apply") for calling Node.js-style functions and getting back a promise: |
---|
690 | |
---|
691 | ```javascript |
---|
692 | return Q.nfcall(FS.readFile, "foo.txt", "utf-8"); |
---|
693 | return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]); |
---|
694 | ``` |
---|
695 | |
---|
696 | If you are working with methods, instead of simple functions, you can easily |
---|
697 | run in to the usual problems where passing a method to another functionâlike |
---|
698 | `Q.nfcall`â"un-binds" the method from its owner. To avoid this, you can either |
---|
699 | use `Function.prototype.bind` or some nice shortcut methods we provide: |
---|
700 | |
---|
701 | ```javascript |
---|
702 | return Q.ninvoke(redisClient, "get", "user:1:id"); |
---|
703 | return Q.npost(redisClient, "get", ["user:1:id"]); |
---|
704 | ``` |
---|
705 | |
---|
706 | You can also create reusable wrappers with `Q.denodeify` or `Q.nbind`: |
---|
707 | |
---|
708 | ```javascript |
---|
709 | var readFile = Q.denodeify(FS.readFile); |
---|
710 | return readFile("foo.txt", "utf-8"); |
---|
711 | |
---|
712 | var redisClientGet = Q.nbind(redisClient.get, redisClient); |
---|
713 | return redisClientGet("user:1:id"); |
---|
714 | ``` |
---|
715 | |
---|
716 | Finally, if you're working with raw deferred objects, there is a |
---|
717 | `makeNodeResolver` method on deferreds that can be handy: |
---|
718 | |
---|
719 | ```javascript |
---|
720 | var deferred = Q.defer(); |
---|
721 | FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver()); |
---|
722 | return deferred.promise; |
---|
723 | ``` |
---|
724 | |
---|
725 | ### Long Stack Traces |
---|
726 | |
---|
727 | Q comes with optional support for âlong stack traces,â wherein the `stack` |
---|
728 | property of `Error` rejection reasons is rewritten to be traced along |
---|
729 | asynchronous jumps instead of stopping at the most recent one. As an example: |
---|
730 | |
---|
731 | ```js |
---|
732 | function theDepthsOfMyProgram() { |
---|
733 | Q.delay(100).done(function explode() { |
---|
734 | throw new Error("boo!"); |
---|
735 | }); |
---|
736 | } |
---|
737 | |
---|
738 | theDepthsOfMyProgram(); |
---|
739 | ``` |
---|
740 | |
---|
741 | usually would give a rather unhelpful stack trace looking something like |
---|
742 | |
---|
743 | ``` |
---|
744 | Error: boo! |
---|
745 | at explode (/path/to/test.js:3:11) |
---|
746 | at _fulfilled (/path/to/test.js:q:54) |
---|
747 | at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30) |
---|
748 | at makePromise.promise.promiseDispatch (/path/to/q.js:496:13) |
---|
749 | at pending (/path/to/q.js:397:39) |
---|
750 | at process.startup.processNextTick.process._tickCallback (node.js:244:9) |
---|
751 | ``` |
---|
752 | |
---|
753 | But, if you turn this feature on by setting |
---|
754 | |
---|
755 | ```js |
---|
756 | Q.longStackSupport = true; |
---|
757 | ``` |
---|
758 | |
---|
759 | then the above code gives a nice stack trace to the tune of |
---|
760 | |
---|
761 | ``` |
---|
762 | Error: boo! |
---|
763 | at explode (/path/to/test.js:3:11) |
---|
764 | From previous event: |
---|
765 | at theDepthsOfMyProgram (/path/to/test.js:2:16) |
---|
766 | at Object.<anonymous> (/path/to/test.js:7:1) |
---|
767 | ``` |
---|
768 | |
---|
769 | Note how you can see the the function that triggered the async operation in the |
---|
770 | stack trace! This is very helpful for debugging, as otherwise you end up getting |
---|
771 | only the first line, plus a bunch of Q internals, with no sign of where the |
---|
772 | operation started. |
---|
773 | |
---|
774 | This feature does come with somewhat-serious performance and memory overhead, |
---|
775 | however. If you're working with lots of promises, or trying to scale a server |
---|
776 | to many users, you should probably keep it off. But in development, go for it! |
---|
777 | |
---|
778 | ## Reference |
---|
779 | |
---|
780 | A method-by-method [Q API reference][reference] is available on the wiki. |
---|
781 | |
---|
782 | [reference]: https://github.com/kriskowal/q/wiki/API-Reference |
---|
783 | |
---|
784 | ## More Examples |
---|
785 | |
---|
786 | A growing [examples gallery][examples] is available on the wiki, showing how Q |
---|
787 | can be used to make everything better. From XHR to database access to accessing |
---|
788 | the Flickr API, Q is there for you. |
---|
789 | |
---|
790 | [examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery |
---|
791 | |
---|
792 | ## Tests |
---|
793 | |
---|
794 | You can view the results of the Q test suite [in your browser][tests]! |
---|
795 | |
---|
796 | [tests]: https://rawgithub.com/kriskowal/q/master/spec/q-spec.html |
---|
797 | |
---|
798 | --- |
---|
799 | |
---|
800 | Copyright 2009-2012 Kristopher Michael Kowal |
---|
801 | MIT License (enclosed) |
---|
802 | |
---|