Suspend - Generator Based Control Flow for Node

While opinions regarding the perils of callback hell (or the ominous sounding "pyramid of doom") vary greatly, it's hard to deny that every once in awhile some library support comes in handy.

After sifting through a dozen-or-so control flow modules, however, it is abundantly clear that callbacks are unavoidable. You can wrap them in promises, chain them, and even get funky with them, but you're still passing around functions to get the job done. The reason for this is quite simple - without using functions, JavaScript simply doesn't allow you to "pause" execution, wait for something else to complete (such as a database query), and then resume where you left off.

Or does it...?

Introducing Suspend

Today I'm happy to announce a new, experimental module for Node that I've been hacking on: suspend.

suspend is a new control flow library that exposes a minimal API around ES6 generators, and is expressly designed to work transparently with Node's existing callback conventions. This allows unobtrusive use of yield execution semantics that works seamlessly with existing Node code bases.

Please note that generators are brand new, and have only been implemented in V8 since 3.19 (so they've been in Node since v0.11.2). In turn, suspend itself is new as well, and, at a minimum, shouldn't be regarded as stable until a stable version of Node itself supports generators.

Super Quick Example

var suspend = require('suspend'),
    fs = require('fs');

suspend(function* (resume) {  
    var data = yield fs.readFile(__filename, resume);

Got It?

Pretty simple - suspend is basically "red light, green light" for asynchronous code execution. yield means stop, and resume means go.

Head on over to the GitHub project for an in-depth overview and documentation.

Thanks for reading!

comments powered by Disqus