It works just like Node Fibers in that it completely eliminates the need for callbacks. But, unlike Node Fibers, it also works on the browser!
Assume that we have a very simple async function that issues an AJAX request to some remote REST API
ajax url callback
This would be a typical composite function that calls the ajax() service several times:
ajax "/user/" + id + "/name"if errcb err ;elseajax "/user/" + id + "/lastname"if errcb errelsecb null name + " " + lastname
Uff. That's a lot of nested callbacks. Let's see if we can do better.
// 1. magically remove the callback from the ajax() serviceajax = syncify ajax// 2. create a composite function. but this time without callbacksreturn ajax "/user/" + id + "/name" + " " + ajax "/user/" + id + "/lastname"// 3. add a callback to the resulting function so we can later use itgetFullName = syncifyrevert getFullName
Both functions ( the one with syncify and the one without syncify ) are equivalent. You can call them like this:
getFullName "aldo" console.log res
Isn't that awesome?
You can use any function. For example:
return ajax"/user/" + id + "/name"toUpperCase
You can even process a collection using Array.map()!
return ajax"/user/" + id + "/friends"mapreturn ajax"/user/" + friend + "/name" + " " + ajax"/user/" + friend + "/lastname"
Or, same as above but using the function we had already defined
return ajax"/user/" + id + "/friends"map getFullName
Well. To be honest. You cannot do just anything. You cannot use Syncify to deal with functions that mutate application state. That means you can exclusively use it with read-only functions.
While this sounds like a limitation, in practice it is not. Syncify is much better at composing queries ( functions that fetch data and draw the UI ) while Async.js is better at composing business logic. You can combine them.
To compensate for this limitation, Syncify has grown some cool tricks. For example, transparent concurrency.
You can make the above method much faster by using syncify.parallel:
var friends = ajax"/user/" + id + "/friends"syncifyparallel// all requests issued within this block will be parallelizedfriendsmapreturn ajax"/user/" + id + "/name" + " " + ajax"/user/" + id + "/lastname"
syncify.parallel() function is explained in this video.
npm install syncify
Syncify has no external dependencies. Just include it like you would any JS library:
If you prefer you can find the .js and .min.js builds in the /build directory.
Takes an async function and returns a syncified version
Takes a syncified function ( or a function that contains nested syncified functions ) and returns an equivalent async function ( one that takes a callback ). This function is the counterpart/opposite of
See video ( top of the page )
See video ( top of the page )
- Functions must be idempotent
- Their arguments must be JSON serializable
- There are a few known bugs ( see issue #18 ). But other than that the code has been used in a dozen apps in production for over 4 months.