您已经犯了一些缺陷。
您应该重写expand以传递URL并传递回调。任何执行异步操作的函数通常
(data, callback)在node
中都具有签名。这基本上可以让您说出我想让此功能执行某项操作,然后告诉我完成该操作的时间。
function expand(urlToParse, callback) { // note we pass in the url this time var short = url.parse(urlToParse); var options = { host: short.hostname, port: 80, path: short.pathname }; // note we store the clientRequest object temporarily var clientRequest = http.get(options, extractRealURL); // Always attach the error handler and forward any errors clientRequest.on("error", forwardError); function extractRealURL(res) { callback(null, res.headers.location); } function forwardError(error) { callback(err); }}在这里,回调应该具有
(err, data)节点中几乎所有回调都具有的签名。我们还添加了必须进行的错误处理。
现在,我们将onRequest更改为实际调用即可正确展开
function onRequest(request, response) { // parse the incoming url. true flag unpacks the query string var parsedUrl = url.parse(request.url, true), // extract the querystring url. // http://localhost:8888/?url=http://t.co/wbDrgquZ urlToExpand = parsedUrl.query.url; // call expand with the url and a callback expand(urlToExpand, writeResponse); function writeResponse(error, newUrl) { // handle the error case properly if (error) { response.writeHead(500, { 'Content-Type': 'text/plain'}); // early return to avoid an else block return response.end(error.message); } response.writeHead(200, { 'Content-Type': 'text/plain'}); // write the new url to the response response.end(newUrl); }}在这里,我们添加了错误处理逻辑,还解压缩了实际的URL,以从查询字符串进行扩展。
通常
doSomething<data, callback<err, result>>,node.js中的工作模式效果很好。
let result = doSomething<data> mayThrow err除了它是异步的之外,它与您在普通阻塞语言中所期望的完全相同。
请注意
ServerResponse,通过这样做,您就无法通过将对象传递给函数的替代选项,从而在扩展函数和服务器响应之间创建了不必要的硬耦合。
扩展功能只应扩展一个URL并返回扩展的URL,它本身不做IO。
完整代码



