

A nice function for Node.js and V8 - EGreg

I've started thinking about how best to implement a real-time chat server for my platform, and found this:<p>V8 + Node.js + Socket.io<p>AWESOME!<p>Personally I'd rather be coding in javascript on the server than erlang ... and with Google's awesome team behind V8, I think it can be fast enough to handle at least 10k users on one machine! (Except of if you are parsing JSON ... there is a post about that recently, and I think the latest V8 might do it a little better.)<p>A lot of people are wary of using javascript though because you have to write lots of nested callbacks to do things in sequence. Well to that I say, let me write a function that sort of does it for you.<p>After writing it, I thought I'd share it here on Hacker News ... hopefully it'll help anyone who's writing in Node.js<p><pre><code>  me.run = function(callables, onSuccess, onError) {
	var k=0, len, ret;
	switch (typeof callables) {
	 case 'object':
		ret = {};
		try {
			for (k in callables) {
				if (typeof(callables[k]) === 'array') {
					ret[k] = callables[k][0].apply(callables[1], callables[k].slice(2));
				} else {
					ret[k] = callables[k].call();
				}
			}
			if (onSuccess) {
				onSuccess(ret);
			}
		} catch (e) {
			if (!onError) {
				throw e;
			}
			onError(e, k, ret);
		}
		break;
	 case 'array':
		ret = [];
		len = callables.length;
		try {
			for (k=0; k&#60;len; ++k) {
				if (typeof(callables[k]) === 'array') {
					ret.push(callables[k][0].apply(callables[1], callables[k].slice(2)));
				} else {
					ret.push(callables[k].call());
				}
			}
			if (onSuccess) {
				onSuccess(ret);
			}
		} catch (e) {
			if (!onError) {
				throw e;
			}
			onError(e, k, ret);
		}
		break;
	}
  };</code></pre>
======
EGreg
Oh sorry guys I was wrong. This is still synchronous. Here's an asynchronous
way of calling N functions in a row:

    
    
      var callback = Pie.callback(3, function() { 
      // do stuff
      }); // makes a function that counts down from 3 and when it reaches 0 calls that inner function
    
      async_thing(1, "foo", callback);
      
      some_other_async_thing(2, callback);
      third_thing(2, callback);

