定义:

    1. 该函子类似于 if else分流控制,意味着二选一
    2. 准备两个不同的函子:正确函子和异常函子
    3. 副作用会用函数变得不纯,容易出现异常,可以使用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)) } }

    1. 如何用Either函子来检索异常的发生呢?
    2. ```javascript
    3. function parstToJson(str) {
    4. try {
    5. // 此处处理正确的值
    6. return Right.of(JSON.parse(str));
    7. } catch (error) {
    8. // 此处处理错误的值
    9. return Left.of({
    10. error: error.message
    11. })
    12. }
    13. }
    14. // 异常函子:用于记录异常信息
    15. class Left {
    16. static of (value) {
    17. return new Left(value);
    18. }
    19. constructor(value) {
    20. this._value = value;
    21. }
    22. map(fn) {
    23. return this
    24. }
    25. }
    26. // 正确函子:实现预期的逻辑
    27. class Right {
    28. static of (value) {
    29. return new Right(value);
    30. }
    31. constructor(value) {
    32. this._value = value;
    33. }
    34. map(fn) {
    35. return Right.of(fn(this._value))
    36. }
    37. }
    38. // 错误
    39. const res = parstToJson('{name: chj}'); // 传递错误的值时,会触发catch 并捕获到错误信息传递给Left函子,并返回记录了错误信息的新函子
    40. console.log(res) // Left { _value: { error: 'Unexpected token n in JSON at position 1' } }
    41. // 正确 // 传递正确的值时,会触发try,并将正确的信息传递给Right函子,并返回记录了正确值的新函子
    42. const res = parstToJson('{"name": "chj"}').map(x => x.name.toUpperCase())
    43. console.log(res) // Right { _value: 'CHJ' }