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

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.

相关问答

更多
  • 需要在API中设置CORS设置,以允许从React应用程序域进行访问。 没有CORS设置,没有来自不同域的AJAX 。 这很简单。 您可以将CORS设置添加到您的公司API(这不太可能发生),或者您可以解决如下所述的问题: CORS只是客户端浏览器的一种机制,可以保护用户免受恶意AJAX攻击。 因此,解决此问题的一种方法是将您的AJAX请求从React应用程序代理到其自己的Web服务器。 正如Vincent建议的那样, create-react-app提供了一种简单的方法:在你的package.json文件 ...
  • 由于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').th ...
  • 您必须更具体地了解用于获取特定答案的框架。 然而,实质上你想要完成的是使用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 spec ...
  • 您可以使用map遍历项目并将它们呈现给DOM {xx.map((x, idx) => {
    {x.username}
    })} 因此,您可以自行决定如何格式化xx其他数据。 让我补充一点,你可能更喜欢componentDidMount到componentWillMount 。 看看这里为什么 You can use map to iterate over the items and render them to the DOM {xx.map((x, idx) => ...
  • 尝试这样的事情 var CommentForm = React.createClass({ getInitialState: function () { return { author: '', text: '' }; }, handleAuthorChange: function (e) { this.setState({ author: e.target.value }); }, handleTextChange: function ...
  • 如果您尝试使用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}/${alcoholPerce ...
  • 回调函数具有签名(错误,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
  • 将字符串文字传递给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 l ...
  • 在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 post p ...
  • 道歉所有 - 但似乎我省略了内容类型.... contentType:“application / json” 当一些物体被重建好并且剩下的不是......时,这是误导性的......嘿嘿 - 这是星期五,它正在工作...... 希望它能帮助别人......所以我现在发现这个有用..... $.ajax({ url: url, type: 'POST', cache: false, **contentType: "application ...

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)