a lightweight promise library for node
kew is a lightweight promise framework with an aim of providing a base set of functionality similar to that provided by the Q library.
Why'd we write it?
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.
So this does everything Q does?
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).
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:
// assuming the getUrlContent() function exists and retrieves the content of a urlvar htmlPromise = getUrlContentmyUrl// we can then filter that through an http parser (our imaginary parseHtml() function) asynchronously (or maybe synchronously, who knows)var tagsPromise = htmlPromisethenparseHtml// and then filter it through another function (getLinks()) which retrieves only the link tagsvar linksPromise = tagsPromisethengetLinks// and then parses the actual urls from the links (using parseUrlsFromLinks())var urlsPromise = linksPromisethenparseUrlsFromLinks// finally, we have a promise that should only provide us with the urls and will run once all the previous steps have ranurlsPromisethen// do something with the urls
As a precursor to all the examples, the following code must be at the top of your page:
var Q = require'kew'
The easiest way to start a promise chain is by creating a new promise with a specified literal using Q.resolve() or Q.reject()
// create a promise which passes a value to the next then() callvar successPromise = Qresolveval// create a promise which throws an error to be caught by the next fail() callvar failPromise = Qrejecterr
In addition, you can create deferreds which can be used if you need to create a promise but resolve it later:
// create the deferredsvar successDefer = Qdefervar failDefer = Qdefer// resolve or reject the defers in 1 secondsetTimeoutsuccessDeferresolve"ok"failDeferreject"this failed"1000// extract promises from the deferredsvar successPromise = successDeferpromisevar failPromise = failDeferpromise
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:
// create the deferredvar defer = Qdefer// some node-style functiongetObjectFromDatabasemyObjectId defermakeNodeResolver// grab the outputdeferpromisethen// successfully retrieved the objectfail// failed retrieving the object
When a promise is resolved, you may call the
.then() method to retrieve the value of the promise:
promisethen// do something with the result here
.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:
Qresolve'a'thenreturn result + 'b'thenreturn result + 'c'then// result should be 'abc'
.then() calls may return promises themselves, allowing for complex nesting of asynchronous calls in a flat manner:
var htmlPromise = getUrlContentmyUrlvar tagsPromise = htmlPromisethenif !validHtmlhtml throw "Invalid HTML"// pretend that parseHtml() returns a promise and is asynchronousreturn parseHtmlhtml
If a promise is rejected for some reason, you may handle the failure case with the
getObjectPromisefailconsole.error"Failed to retrieve object" e
.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:
getObjectPromisefailreturn retryGetObjectobjIdthen// yay, we received an objectfail// the retry failed :(console.error"Retrieving the object '" + objId + "' failed"
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:
getObjectPromise// this will throw an error to the uncaught exception handler if the getObjectPromise call is asynchronousend
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:
var connection = dbconnectvar itemPromise = dbgetItemitemIdfindbclose
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:
var promises =promisespushgetUrlContenturl1promisespushgetUrlContenturl2promisespushgetUrlContenturl3Qallpromisesthen// content === content for url 1// content === content for url 2// content === content for url 3
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):
var promises =promisespushgetUrlContenturl1promisespushgetUrlContenturl2promisespushgetUrlContenturl3Qallpromisesfailconsole.log"Failed retrieving a url" e
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:
getUrlContenturl1fail// Retry again after 200 milissecondsreturn Qdelay200thenreturn getUrlContenturl1
If two arguments are passed, the first will be used as the return value, and the second will be the delay in milliseconds.
Qdelayobj 20thenconsole.logresult // logs `obj` after 20ms
// Assume someFn() is a synchronous 2 argument function you want to delay.QfcallsomeFn arg1 arg2thenconsole.log'someFn(' + arg1 + ', ' + arg2 + ') = ' + result
You can also use
Q.fcall() with functions that return promises.
Q.nfcall() can be used to convert node-style callbacks into promises:
QnfcallfswriteFile '/tmp/myFile' 'content'thenconsole.log'File written successfully'failconsole.log'Failed to write file' err
() can be used to convert node-style callbacks into promises:
Qnfcallreturn 'a' Qresolve'b'spread// ...
Questions, comments, bug reports, and pull requests are all welcome. Submit them at the project on GitHub.
Bug reports that include steps-to-reproduce (including code) are the best. Even better, make them in the form of pull requests that update the test suite. Thanks!
Copyright 2013 The Obvious Corporation.
Licensed under the Apache License, Version 2.0.
See the top-level file