FWIW any other runtime/framework will do what you suggest. For example, Rhino.
FWIW any other runtime/framework will do what you suggest. For example, Rhino.
Anyway, with generators and promises you can write asynchronous code which looks like synchronous code but which under the covers is still completely async and callback-driven. We use it in gjs (a GNOMEy JS runtime built on top of Spidermonkey).
Instead of workflows like:
function onServerRequest(req, res) {
db.query("get filename", function(result) {
fs.readContents(result, function (data) {
res.write(data);
});
});
}
which can get pretty nasty if you're running things in serial, or want to run a couple of things in parallel but then run something serially, you can have a workflow more like this: function onServerRequest(req, res) {
var queryPromise = db.queryPromise("get filename");
var filename = yield queryPromise;
var data = yield db.readContentsPromise(filename);
res.write(data);
}
The main difference between the two is that the async functions in the latter return promises instead of nothing. The db.queryPromise() function itself would probably look something like: function queryPromise(query) {
var promise = new Promise();
db.query(query, function(result) {
promise.putValue(result);
});
return promise;
}
I imagine you could probably write a function to automatically generate promise wrappers for existing async functions as long as they followed a certain schema, and Node's functions tend to do well with that.Anyway, the onServerRequest() function would itself be wrapped in a function which took the generator values from it and returned its own promise. This way you could stack promises all the way up.
The gjs implementation of this is here: http://git.gnome.org/browse/gjs/tree/modules/promise.js
This is pretty similar to Twisted's inlineCallbacks if you're familiar with them in Python.