1 kew: a lightweight (and super fast) promise/deferred framework for node.js
2 ==================================
4 [![Build Status](https://travis-ci.org/Medium/kew.svg)](https://travis-ci.org/Medium/kew)
6 **kew** is a lightweight promise framework with an aim of providing a base set of functionality similar to that provided by the [Q library](https://github.com/kriskowal/q "Q").
8 A few answers (for a few questions)
13 During our initial usage of **Q** we found that it was consuming 80% of the cpu under load (primarily in chained database callbacks). We spent some time looking at patching **Q** and ultimately found that creating our own lightweight library for server-usage would suit our needs better than figuring out how to make a large cross-platform library more performant on one very specific platform.
15 *So this does everything Q does?*
17 Nope! **Q** is still an awesome library and does *way* more than **kew**. We support a tiny subset of the **Q** functionality (the subset that we happen to use in our actual use cases).
22 At its core, a *Promise* is a promise to return a value at some point in the future. A *Promise* represents a value that will be (or may return an error if something goes wrong). *Promises* heavily reduce the complexity of asynchronous coding in node.js-like environments. Example:
25 // assuming the getUrlContent() function exists and retrieves the content of a url
26 var htmlPromise = getUrlContent(myUrl)
28 // we can then filter that through an http parser (our imaginary parseHtml() function) asynchronously (or maybe synchronously, who knows)
29 var tagsPromise = htmlPromise.then(parseHtml)
31 // and then filter it through another function (getLinks()) which retrieves only the link tags
32 var linksPromise = tagsPromise.then(getLinks)
34 // and then parses the actual urls from the links (using parseUrlsFromLinks())
35 var urlsPromise = linksPromise.then(parseUrlsFromLinks)
37 // finally, we have a promise that should only provide us with the urls and will run once all the previous steps have ran
38 urlsPromise.then(function (urls) {
39 // do something with the urls
46 As a precursor to all the examples, the following code must be at the top of your page:
49 var Q = require('kew')
52 ### Convert a literal into a promise
54 The easiest way to start a promise chain is by creating a new promise with a specified literal using Q.resolve() or Q.reject()
57 // create a promise which passes a value to the next then() call
58 var successPromise = Q.resolve(val)
60 // create a promise which throws an error to be caught by the next fail() call
61 var failPromise = Q.reject(err)
64 In addition, you can create deferreds which can be used if you need to create a promise but resolve it later:
67 // create the deferreds
68 var successDefer = Q.defer()
69 var failDefer = Q.defer()
71 // resolve or reject the defers in 1 second
72 setTimeout(function () {
73 successDefer.resolve("ok")
74 failDefer.reject(new Error("this failed"))
77 // extract promises from the deferreds
78 var successPromise = successDefer.promise
79 var failPromise = failDefer.promise
82 If you have a node-style callback (taking an **Error** as the first parameter and a response as the second), you can call the magic `makeNodeResolver()` function on a defer to allow the defer to handle the callbacks:
85 // create the deferred
88 // some node-style function
89 getObjectFromDatabase(myObjectId, defer.makeNodeResolver())
93 .then(function (obj) {
94 // successfully retrieved the object
97 // failed retrieving the object
101 ### Handling successful results with `.then()`
103 When a promise is resolved, you may call the `.then()` method to retrieve the value of the promise:
106 promise.then(function (result) {
107 // do something with the result here
111 `.then()` will in turn return a promise which will return the results of whatever it returns (asynchronously or not), allowing it to be chained indefinitely:
115 .then(function (result) {
118 .then(function (result) {
121 .then(function (result) {
122 // result should be 'abc'
126 In addition, `.then()` calls may return promises themselves, allowing for complex nesting of asynchronous calls in a flat manner:
129 var htmlPromise = getUrlContent(myUrl)
131 var tagsPromise = htmlPromise.then(function (html) {
132 if (!validHtml(html)) throw new Error("Invalid HTML")
134 // pretend that parseHtml() returns a promise and is asynchronous
135 return parseHtml(html)
139 ### Handling errors with `.fail()`
141 If a promise is rejected for some reason, you may handle the failure case with the `.fail()` function:
146 console.error("Failed to retrieve object", e)
150 Like `.then()`, `.fail()` also returns a promise. If the `.fail()` call does not throw an error, it will pass the return value of the `.fail()` handler to any `.then()` calls chained to it:
155 return retryGetObject(objId)
157 .then(function (obj) {
158 // yay, we received an object
161 // the retry failed :(
162 console.error("Retrieving the object '" + objId + "' failed")
167 If you've reached the end of your promise chain, you may call `.end()` which signifies that the promise chain is ended and any errors should be thrown in whatever scope the code is currently in:
171 // this will throw an error to the uncaught exception handler if the getObjectPromise call is asynchronous
175 ### `.fin()` when things are finished
177 You may attach a handler to a promise which will be ran regardless of whether the promise was resolved or rejected (but will only run upon completion). This is useful in the cases where you may have set up resources to run a request and wish to tear them down afterwards. `.fin()` will return the promise it is called upon:
180 var connection = db.connect()
182 var itemPromise = db.getItem(itemId)
188 Other utility methods
191 ### `.all()` for many things
193 If you're waiting for multiple promises to return, you may pass them (mixed in with literals if you desire) into `.all()` which will create a promise that resolves successfully with an array of the results of the promises:
197 promises.push(getUrlContent(url1))
198 promises.push(getUrlContent(url2))
199 promises.push(getUrlContent(url3))
202 .then(function (content) {
203 // content[0] === content for url 1
204 // content[1] === content for url 2
205 // content[2] === content for url 3
209 If any of the promises fail, Q.all will fail as well (so make sure to guard your promises with a `.fail()` call beforehand if you don't care whether they succeed or not):
213 promises.push(getUrlContent(url1))
214 promises.push(getUrlContent(url2))
215 promises.push(getUrlContent(url3))
219 console.log("Failed retrieving a url", e)
223 ### `.delay()` for future promises
225 If you need a little bit of delay (such as retrying a method call to a service that is "eventually consistent") before doing something else, ``Q.delay()`` is your friend:
230 // Retry again after 200 milisseconds
231 return Q.delay(200).then(function () {
232 return getUrlContent(url1)
237 If two arguments are passed, the first will be used as the return value, and the
238 second will be the delay in milliseconds.
241 Q.delay(obj, 20).then(function (result) {
242 console.log(result) // logs `obj` after 20ms
246 ### `.fcall()` for delaying a function invocation until the next tick:
248 // Assume someFn() is a synchronous 2 argument function you want to delay.
249 Q.fcall(someFn, arg1, arg2)
250 .then(function (result) {
251 console.log('someFn(' + arg1 + ', ' + arg2 + ') = ' + result)
255 You can also use ``Q.fcall()`` with functions that return promises.
257 ### `.ncall()` and `.nfcall()` for Node.js callbacks
259 ``Q.nfcall()`` can be used to convert node-style callbacks into promises:
262 Q.nfcall(fs.writeFile, '/tmp/myFile', 'content')
264 console.log('File written successfully')
266 .fail(function (err) {
267 console.log('Failed to write file', err)
271 If your Node-style callback needs a `this` context, you can use `Q.ncall`:
274 Q.ncall(redis.del, redis, 'my-key')
275 .then(function () { return true })
276 .fail(function () { return false })
280 ### `.spread()` for arrays of promises
282 ``()`` can be used to convert node-style callbacks into promises:
285 Q.nfcall(function () {
286 return ['a', Q.resolve('b')]
288 .spread(function (a, b) {
297 Questions, comments, bug reports, and pull requests are all welcome.
298 Submit them at [the project on GitHub](https://github.com/Obvious/kew/).
300 Bug reports that include steps-to-reproduce (including code) are the
301 best. Even better, make them in the form of pull requests that update
302 the test suite. Thanks!
308 [Jeremy Stanley](https://github.com/azulus)
310 [The Obvious Corporation](http://obvious.com/).
316 Copyright 2013 [The Obvious Corporation](http://obvious.com/).
318 Licensed under the Apache License, Version 2.0.
319 See the top-level file `LICENSE.TXT` and
320 (http://www.apache.org/licenses/LICENSE-2.0).