coffeescript return function callback acting strange

允我心安 提交于 2019-12-13 04:55:05

问题


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

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

coffeescript translate it to that:

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

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

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 

will translate into:

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

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


回答1:


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.




回答2:


If you want to return "hello #{user.name}" from the anonymous function and return nothing from foo, it's sufficient to do:

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

Note that most likely, the return value of the callback (the anonymous function) won't be accessible to you. The callback is called by the findById function, and this function most likely discards the callback's return value.

Also, in principle, it doesn't matter if a function returns a weird value, as long as it's never used. You only need to put explicit return or undefined on the last line of a function body if you want to create a really clean API.



来源:https://stackoverflow.com/questions/19471033/coffeescript-return-function-callback-acting-strange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!