简介
either两者中的任意一个,类似于if else的处理
异常会让函数变得不纯,either函子可以用来做异常处理
举例
//either函子
class Left {
static of(value) {
return new Left(value)
}
constructor(value) {
this._value = value;
}
map(fn) {
return this
}
}
class Right {
static of(value) {
return new Right(value)
}
constructor(value) {
this._value = value;
}
map(fn) {
return Right.of(fn(this._value))
}
}
function parseJSON(str) { //定义一个函数
try {
return Right.of(JSON.parse(str))
} catch (error) {
//用来存储错误信息
return Left.of({ error: error.message })
}
}
let str4 = '{"name":"loki"}'
let str5 = { "name": "loki" }
let str6 = '{"name":"lion"}'
let result5 = parseJSON(str4)
console.log(result5); //Right { _value: { name: 'loki' } }
let result6 = parseJSON(str5) //传入错误的数据
console.log(result6); //Left { _value: { error: 'Unexpected token o in JSON at position 1' } }
//捕获错误信息
let result7 = parseJSON(str6)
console.log(result7); //Right { _value: { name: 'lion' } }
either函子本质上就是两个函子组合的,一个函子走正确的逻辑,另外一个函子用来捕捉错误信息
谢谢观看,如有不足,敬请指教