Hacker News new | ask | show | jobs
by MatthewPhillips 5241 days ago
> So for instance all calls to the server API have to be callback style; if you have to make serial calls, you can't avoid nested callbacks.

I hear this over and over again but I frankly do not get it. I write JavaScript every day and got over the nested callback problem ages ago. I don't say this to refute the point; I legitimately don't get it and feel like maybe I'm doing something wrong because I don't encounter the problem. Here's how I write stuff that requires several callbacks:

  function TakesAWhile() {
 
  }
 
  TakesAWhile.prototype = {
 	start: function() {
 		var xhr = new XMLHttpRequest();
 		xhr.open('POST', 'api/foo', true);
 		xhr.onreadystatechange = this.posted.bind(this);
 		xhr.send('bar');
 	},
 	
 	posted: function(e) {
 		if(!(e.target.readyState !== 4)) {
 			this.complete('error :-(');
 			return;
 		}
 		
 		db.saveSomething(someObject, this.saved.bind(this));
 	},
 	
 	saved: function(e) {
 		db.getFreshCopy('foo', this.got.bind(this));
 	},
	
 	got: function(e) {
 		var foo = e.target.result;
 		this.complete(foo);
 	}
 };
Then I consume it like this:

  var stuff = new TakesAWhile();
  stuff.complete = function(foo) {
  	console.log('All complete!');
  };
  stuff.start();