定义:
- 该函子类似于 if else分流控制,意味着二选一
- 准备两个不同的函子:正确函子和异常函子
- 副作用会用函数变得不纯,容易出现异常,可以使用Either函子来处理异常 ```javascript // 注意:Left,Right只是列举的两个函子,并不是固定的写法
// 异常函子:用于记录异常信息 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)) } }
如何用Either函子来检索异常的发生呢?```javascriptfunction parstToJson(str) {try {// 此处处理正确的值return Right.of(JSON.parse(str));} catch (error) {// 此处处理错误的值return Left.of({error: error.message})}}// 异常函子:用于记录异常信息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))}}// 错误const res = parstToJson('{name: chj}'); // 传递错误的值时,会触发catch 并捕获到错误信息传递给Left函子,并返回记录了错误信息的新函子console.log(res) // Left { _value: { error: 'Unexpected token n in JSON at position 1' } }// 正确 // 传递正确的值时,会触发try,并将正确的信息传递给Right函子,并返回记录了正确值的新函子const res = parstToJson('{"name": "chj"}').map(x => x.name.toUpperCase())console.log(res) // Right { _value: 'CHJ' }
