Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Last active December 25, 2015 22:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piscisaureus/7049638 to your computer and use it in GitHub Desktop.
Save piscisaureus/7049638 to your computer and use it in GitHub Desktop.
var http = require('http');
var cache = {};
function curl(url, cb) {
if (cache[url])
// WRONG: synchronous callback
return cb(null, cache[url]);
var data = '';
http.get(url, function(res) {
res.setEncoding('utf8');
res.on('data', function(s) {
data += s;
});
res.on('end', function() {
cache[url] = data;
cb(null, data);
});
// WRONG: are you sure that 'end' and 'error' are mutually exclusive?
res.on('error', function(err) {
cb(err);
});
});
// WRONG: the request object may emit 'error', but there is no
// handler for it.
}
// Usage:
curl('http://www.google.com', console.log);
var Zone = require('./').Zone;
var http = require('http');
var cache = {};
function curl(url, cb) {
new Zone(function CurlZone() {
if (cache[url])
return zone.return(cache[url]);
var data = '';
var req = http.get(url, function(res) {
res.setEncoding('utf8');
res.on('data', function(s) {
data += s;
});
res.on('end', function() {
cache[url] = data;
zone.return(data);
});
});
}).setCallback(cb);
}
// Usage:
curl('http://www.google.com/', console.log);
curl('http://does/not/exist/', console.log);
@piscisaureus
Copy link
Author

I agree it's a bit vague. The key is this line:

curl('http://does/not/exist/', console.log);

Because the async op is wrapped in a zone, the error is passed to the callback as the first argument, which in the example happens to be console.log.

So what you're seeing is basically the output of:

console.log(error);

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