db.findUser(id).then(R.pipe(
R.ifElse(firstTestHere, Either.Right, () => Either.Left(err)),
R.map(R.ifElse(secondTestHere, obj => obj, () => Either.Left(err))),
console.log
))如果第一个测试没有通过,它将返回Either.Left,而第二个测试将不会被调用。它将公布:
_Right {value: user}
但如果第一次通过,而第二次没有通过,它将变成:
_Right {value: _Left {value: err}}
我希望它只输出_Left {value: err},如何修复代码,还是有任何方法将右转到左?
发布于 2017-05-20 07:00:36
您注意到的是,map无法将两个Either实例一起“扁平化”。要做到这一点,您将需要使用chain。
db.findUser(id).then(R.pipe(
R.ifElse(firstTestHere, Either.Right, () => Either.Left(err)),
R.chain(R.ifElse(secondTestHere, Either.Right, () => Either.Left(err))),
console.log
))这种将一系列调用组合在一起的模式也可以通过composeK/pipeK来实现,其中要组合的每个函数都必须采用Monad m => a -> m b形式,即从给定的值生成一些单变量(如Either)的函数。
使用R.pipeK,您的示例可以修改为如下所示:
// helper function to wrap up the `ifElse` logic
const assertThat = (predicate, error) =>
R.ifElse(predicate, Either.Right, _ => Either.Left(error))
const result = db.findUser(id).then(R.pipeK(
assertThat(firstTestHere, err),
assertThat(secondTestHere, err)
));https://stackoverflow.com/questions/44073615
复制相似问题