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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I agree it's a bit vague. The key is this line:
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: