Coffeescript隐含的回报对性能和副作用产生影响(Coffeescript implicit returns impact on performance and side effects)

我目前正在开发一个使用Express.js和Mongoose的node.js Web服务。 最近,我想我会尝试使用CoffeeScript,因为我听说有一些好处。 但是,我注意到了一些有点令人不安的事情,我很好奇是否有人可以澄清。

这是我在普通javascript中的一条路线:

router.post('/get/:id', decorators.isManager, function(req, res) {
    Group.findById(req.params.id, function(err, grp) {
            if(err) res.status(500).end();
            if(grp == null) res.status(500).send('The group could not be found');
            res.send(grp);
    });
});

但是,使用以下(几乎相当于coffeescript):

router.post '/get/:id', decorators.isManager, (req, res) ->
  Group.findById req.params.id, (err, grp) ->
    res.status(500).end() if err
    res.status(500).send 'The group could not be found' if not grp?
    res.send grp

将此重新编译为javascript会返回以下内容:

router.post('/get/:id', decorators.isManager, function(req, res) {
    return Group.findById(req.params.id, function(err, grp) {
            if(err) res.status(500).end();
            if(grp == null) res.status(500).send('The group could not be found');
            return res.send(grp);
    });
});

这些额外的回报会影响我的应用程序的性能吗,它会改变它的工作方式吗? 我测试了它,似乎是相同的响应时间但是我不确定这会对多个嵌套查询产生什么影响。 谢谢!


I am currently working on a node.js web service which utilizes Express.js and Mongoose. Recently, I figured I would try my hand at CoffeeScript, as I have heard that there are some benefits to be had. However, I have noticed something a little unsettling, and I was curious if someone could clarify.

Here is one of my routes in plain javascript:

router.post('/get/:id', decorators.isManager, function(req, res) {
    Group.findById(req.params.id, function(err, grp) {
            if(err) res.status(500).end();
            if(grp == null) res.status(500).send('The group could not be found');
            res.send(grp);
    });
});

However, with the following (nearly equivalent coffeescript):

router.post '/get/:id', decorators.isManager, (req, res) ->
  Group.findById req.params.id, (err, grp) ->
    res.status(500).end() if err
    res.status(500).send 'The group could not be found' if not grp?
    res.send grp

Re-compiling this to javascript returns the following:

router.post('/get/:id', decorators.isManager, function(req, res) {
    return Group.findById(req.params.id, function(err, grp) {
            if(err) res.status(500).end();
            if(grp == null) res.status(500).send('The group could not be found');
            return res.send(grp);
    });
});

Will those extra returns effect the performance of my application, does it alter the way it works? I tested it, it seems to be the same response time however I am not sure the impact this will have on multiple nested queries. Thank you!


原文:https://stackoverflow.com/questions/29070113
2023-11-24 13:11

满意答案

将字符串文字传递给getURI方法:

Api.getURI('outline')

调用Api.getURI(outline)使解释器查找outline变量,这在当前作用域中是未定义的(因此是ReferenceError)。

Protip:像ESLint一样, linter会尽早发现这个错误。


Pass string literal to getURI method:

Api.getURI('outline')

Calling Api.getURI(outline) makes interpreter look for outline variable, which is undefined in the current scope (hence ReferenceError).

Protip: linter, like ESLint, would catch this error early.

相关问答

更多

ReactJS API数据获取CORS错误(ReactJS API Data Fetching CORS error)

需要在API中设置CORS设置,以允许从React应用程序域进行访问。 没有CORS设置,没有来自不同域的AJAX 。 这很简单。 您可以将CORS设置添加到您的公司API(这不太可能发生),或者您可以解决如下所述的问题: CORS只是客户端浏览器的一种机制,可以保护用户免受恶意AJAX攻击。 因此,解决此问题的一种方法是将您的AJAX请求从React应用程序代理到其自己的Web服务器。 正如Vincent建议的那样, create-react-app提供了一种简单的方法:在你的package.j...

ReactJS componentDidMount和Fetch API(ReactJS componentDidMount and Fetch API)

由于fetch是异步的,你需要做这样的事情: componentDidMount() { APIHelper.fetchFood('Dairy').then((data) => { this.setState({dairyList: data}); }); }, Since fetch is async you'll need to do something like this: componentDidMount() { APIHelper.fetchFood('Dairy...

如何将List 传递给api url?(How can I pass a List to an api url?)

您必须更具体地了解用于获取特定答案的框架。 然而,实质上你想要完成的是使用slugs .. 根据您使用的框架,您可以搜索:“框架”slug,“框架”slugs,“框架”slugify。 例如,这解释了如何在Spring MVC框架的控制器上使用slug: https://github.com/resthub/resthub.org/blob/master/spring-stack.rst#sluggable-controller 希望这可以帮助。 You would have to be more...

从ReactJs中提取API中的数据(Extract data from API in ReactJs)

您可以使用map遍历项目并将它们呈现给DOM {xx.map((x, idx) => {<div key={idx}> {x.username} </div> })} 因此,您可以自行决定如何格式化xx其他数据。 让我补充一点,你可能更喜欢componentDidMount到componentWillMount 。 看看这里为什么 You can use map to iterate over the items and render them to the DOM {xx.map((x, id...

如何将道具传递给reactjs处理程序?(How to pass Props to reactjs handler?)

尝试这样的事情 var CommentForm = React.createClass({ getInitialState: function () { return { author: '', text: '' }; }, handleAuthorChange: function (e) { this.setState({ author: e.target.value }); }, handleTextChange: fun...

将多个参数传递给后端API reactjs(Pass multiple argument to back-end API reactjs)

如果您尝试使用ES6模板功能,则需要使用反标记而不是单引号: `/api/beers/add/${name}/${country}/${color}/${alcoholPercent}` If you are trying to use the ES6 templating feature, you need to use back ticks and not single quotes: `/api/beers/add/${name}/${country}/${color}/${alcohol...

如何从Reactjs调用Web服务(How to call the webservice from Reactjs)

回调函数具有签名(错误,res)将代码更改为该签名并更改注释中提到的import语句AS它应该工作 The callback function has the signature (err, res) Change your code to that signature & change the import statement AS mentioned in the comments and it should work

如何将API从API传递给Action(ReactJS)(How pass URL from API to Action (ReactJS))

将字符串文字传递给getURI方法: Api.getURI('outline') 调用Api.getURI(outline)使解释器查找outline变量,这在当前作用域中是未定义的(因此是ReferenceError)。 Protip:像ESLint一样, linter会尽早发现这个错误。 Pass string literal to getURI method: Api.getURI('outline') Calling Api.getURI(outline) makes interpre...

Django在一个像+ reactjs的API中。(Django in an API like + reactjs. How to generate a csrf token)

在CBV上装饰调度方法,它应该解决你的帖子问题 def MyView(View) @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(MyView, self).dispatch(request, *args, **kwargs) decorate dispatch method on CBV, it should resolve your p...

传递给WEb API Action时,在JSON中丢失值(Losing values in JSON when passing to WEb API Action)

道歉所有 - 但似乎我省略了内容类型.... contentType:“application / json” 当一些物体被重建好并且剩下的不是......时,这是误导性的......嘿嘿 - 这是星期五,它正在工作...... 希望它能帮助别人......所以我现在发现这个有用..... $.ajax({ url: url, type: 'POST', cache: false, **contentType: "applic...

相关文章

更多

Solr Performance Factors(Solr 性能因素)

Schema Design Considerations(数据模型方面考虑) indexed fiel ...

Riak, haproxy, and client side applications

转载:http://blog.dloh.org/Riak,-haproxy,-and-client-s ...

Supra Skytop Shoes All White Gunny are a top performance

The Skytop “Crimson” is an all white leather affair ...

SOLR Performance Benchmarks – Single vs. Multi-core Index Shards

http://www.derivante.com/2009/05/05/solr-performanc ...

《新火星人-After Effects 5.5 影视合成风暴 3CD》[ISO]

本套教材是针对应用最广泛的影视合成软件Adobe After Effect 5.5版的权威学习教材, ...

《深入浅出CoffeeScript》(CoffeeScript: Accelerated JavaScript Development)扫描版[PDF]

中文名: 深入浅出CoffeeScript 原名: CoffeeScript: Accelera ...

对Hadoop-HDFS性能造成重大影响的杀手-Shell

在测试Hadoop时, 使用NameNode身上的dfshealth.jsp管理页面发现,DataNo ...

CISCO ROUTER 中的隐含命令

[A] aaa accounting delay-start [12.1] [hidden] gl ...

升级 Solr 1.4 后性能有所提升

原文出处:http://blog.chenlb.com/2009/12/updatedsolr-1-4 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本