coffeescript返回函数回调函数奇怪 [英] coffeescript return function callback acting strange

查看:223
本文介绍了coffeescript返回函数回调函数奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的函数:

let's say i have a simple function like that:

foo ->  
  User.findById someId, (err, user) ->
    return "hello #{user.name}"  

coffeescript 翻译成:

coffeescript translate it to that:

foo(function() {
  return User.findById(someId, function(err, user) {
   return "hello " + user.name;
  });
});

所以这里有2个返回,但是我只是想返回hello回调。

so there are 2 returns here from some reason, but i just want to return the "hello" after the callback.

唯一的方法是我发现没有返回一个函数,当我使用它是关闭它与 return (这是一个奇怪的解决方法)。所以:

the only way i found not to return a function when i use it is by closing it with a return (that is a weird workaround). so:

foo ->  
  User.findById someId, (err, user) ->
    return "hello #{user.name}"
  return 

into:

foo(function() {
  User.findById(someId, function(err, user) {
    return "hello " + user.name;
  });
});

有一个更好的办法,除了关闭一个函数与 return key?

is there a better way to do that other than closing a function with a return key?

推荐答案

很好,这是Coffeescript的工作方式,它总是返回最后一个表达式一个函数,除非你返回 undefined 带有一个空的 return 或其他东西。

It's fine, that's how Coffeescript works, it always returns the last expression of a function unless you return undefined with an empty return, or something else.

这篇关于coffeescript返回函数回调函数奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆