coffeescript返回函数回调函数奇怪 [英] coffeescript return function callback acting strange
问题描述
假设我有一个简单的函数:
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屋!