Last active
December 25, 2015 22:29
-
-
Save piscisaureus/7049638 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
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.