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);
@crandmck
Copy link

crandmck commented May 9, 2014

So bad.js gives this:

$ node bad.js
events.js:85
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:41:10)
at Object.onlookup as oncomplete

And zoneified.js gives this:
$ node zoneified.js
{ [Error: getaddrinfo ENOTFOUND]
stack: 'Error: getaddrinfo ENOTFOUND\n at errnoException (dns.js:41:10)\n at Object.onlookup as oncomplete',
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'does' }

Is this this the expected result? If so, then I don' t understand.

@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