栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

了解Javascript和Node.js中的回调

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

了解Javascript和Node.js中的回调

您已经犯了一些缺陷。

您应该重写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。

完整代码



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614037.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号