我有一些Play Scala的项目,我发现在模型中使用scala Either[A, B]
构造非常有用,这样在我的控制器中我有类似的东西(例如)
val modelResult:Either[String, String] = ...
modelResult match {
case Left(a) => Ok(... do something here that is meant for a 200 ....)
case Right(err) => BadRequest(display an error in a 400)
}
什么是在Javascript中做类似的事情的好方法(我使用Koa框架)
对于那些不熟悉Either
构造https://www.scala-lang.org/api/2.12.0/scala/util/Either.html的人
看看JavaScript的众多FP库之一。 Rambda是一个受欢迎的(见docs/#either)。您也可以查看daggy来建模联产品。
Thinking in Rambda为Rambda提供了一个很好的介绍
这样的事怎么样?
class Either {}
class Left extends Either {
constructor(leftValue) {
super()
this.leftValue = leftValue;
}
match(lHandler, unused) {
return lHandler(this.leftValue);
}
}
class Right extends Either {
constructor(rightValue) {
super()
this.rightValue = rightValue;
}
match(unused, rHandler) {
return rHandler(this.rightValue);
}
}
用法:
const either = ... // e.g. new Left('Test');
either.match(
left => console.log(left),
right => console.warn('An error occurred'),
);
为了使这个真正有用,我建议添加map
,flatMap
等。