如何避免隐式“返回”在条件表达式中的coffeescript? [英] How to avoid an implicit "return" in coffeescript in conditional expressions?

查看:123
本文介绍了如何避免隐式“返回”在条件表达式中的coffeescript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个函数,它具有递延的返回值,并且在函数中有很多嵌套的条件表达式:

I am implementing a function that has deferred value to return and within the function I have many nested conditional expressions:

例如:

deferred = Q.defer()
FS.readFile("foo.txt", "utf-8", (error, text) ->
    if error
      deferred.reject(new Error(error))
    else
      deferred.resolve(text)
)
return deferred.promise

这将编译成:

var deferred;

deferred = Q.defer();

FS.readFile("foo.txt", "utf-8", function(error, text) {
  if (error) {
    --> return <-- deferred.reject(new Error(error));
  } else {
    --> return <-- deferred.resolve(text);
  }
});

return deferred.promise;

我只需要最后一次返回,而不是if / else返回(即 > return< - 在编译的代码中)

I need only the last return, but not the if/else returns (i.e. --> return <-- in the compiled code)

如何避免这种行为(隐性返回,不需要它们)coffeescript编译器?

How can I avoid such a behavior (implicit returns where they are do not needed) of the coffeescript compiler?

推荐答案

Coffeescript自动返回最后一个表达式的结果,所以如果你不想返回结果 if 那么你需要添加另一个表达式。在这种情况下,只需添加 return

Coffeescript automatically returns the result of the last expressions, so if you don't want it to return the results of the if then you need to add another expressions. In this case, just add return.

FS.readFile "foo.txt", "utf-8", (error, text) ->
  if error
    deferred.reject new Error(error)
  else
    deferred.resolve text
  return

此外,错误已经是错误因此您可以直接拒绝它。

Also, error is already an Error object, so you can just reject it directly.

deferred.reject(error)

这篇关于如何避免隐式“返回”在条件表达式中的coffeescript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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