Module stick/middleware/continuation
Provide support for JavaScript 1.7 generator actions.
This middleware supports two types of yield values from generators: Promises and JSGI response objects.
If a generator action yields a promise, this middleware adds a listener to that promise that will feed the value back to the generator once the promise is resolved. If the promise resolves to an error, the error is thrown in the generator.
For example, if promise
is a promise, the yield
statement will interrupt execution
of the action until the promise is resolved, at which point the generator is resumed
with the value of the promise being assigned to the resolved
variable.
var resolved = yield promise;
If a generator action yields a JSGI response, the response is sent to the client.
To be able to yield more than one response from the same generator, the generator
has to be associated with a continuation id and stored in the user's session.
This is done by calling continuation.activate()
before yielding the first
response. The activate()
method tells the middleware to store the generator
in the user's session and returns a contination id.
For subsequent invocations of the generator, the continuation id has to be set as
query string parameter with name _c
. When suspended generator is resumed,
the new request object is passed in as value for the last yield statement.
function continuation(request) {
var c = app.continuation.activate();
while(true) {
request = yield response.html(linkTo(app, {_c: c}));
}
}
See http://blog.ometer.com/2010/11/28/a-sequential-actor-like-api-for-server-side-javascript/ for background.