Skip to content

Instantly share code, notes, and snippets.

@cgbystrom
Created December 1, 2010 20:56
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgbystrom/724208 to your computer and use it in GitHub Desktop.
Save cgbystrom/724208 to your computer and use it in GitHub Desktop.
node.js vs Python with Greenlets
/*
node.js vs Python with Greenlets (say gevent)
I don't get why node.js is being so hyped.
Sure, the idea of writing things in JavaScript both on the client and server-side is really nice.
And JavaScript really fit an event-driven environment with its browser heritage.
But why on earth is boomerang code so appealing to write? I don't get. Am I missing something obvious?
All examples of node.js I see are littered with callbacks yet Ryan Dahl thinks coroutines suck. It doesn't add up for me.
Would anyone mind explaining how node.js below is superior to the Python code at the bottom?
Semi-pseudo node.js code with express.js follows:
*/
var memcached = ...; // From node-memcached
var mongo = ...; // From mongoose
app.get('/', function(req, res) {
var a = null, b = null, c = null, d = null;
memcached.get('mykey1', function(err, result) {
if (err) {
sys.puts('Naive error');
return;
}
a = result;
memcached.get('mykey2', function(err, result) {
if (err) {
sys.puts('Naive error');
return;
}
b = result;
mongo.find({name: 'Joe'}).each(function(doc) {
// Errors handled by mongoose
c = doc.age;
mongo.find({name: 'Julia'}).each(function(doc) {
d = doc.lastname;
res.send('Hello World! ' + a + b + c + d);
});
});
});
});
});
########################################################################
# Compared to a Python semi-pseudo example based on Flask and gevent.
@app.route("/")
def hello():
a = memcached.get('mykey1')
b = memcached.get('mykey2')
c = mongo.find(name='Joe').first().age
d = mongo.find(name='Julia').first().lastname
return "Hello World! %s%s%s%s" % (a, b, c, d)
@alexei-sch
Copy link

@ephetic the original python code is not synchonous. It's using gevent (coroutine-based async library) which does monkey-patching of blocking python functions and replaces them with async counterparts. As a result code looks like synchronous but is run in a same way as Node.js does. And for me looks much more elegant than JS one (even in the last sample by @stevage).

@worldmind
Copy link

May wil be interesting for someone who want make python async more fast - https://github.com/MagicStack/uvloop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment