[JS Compose] 3. Use chain for composable error handling with nested Eithers (flatMap)

We refactor a function that uses try/catch to a single composed expression using Either. We then introduce the chain function to deal with nested Eithers resulting from two try/catch calls.

 

For example we have this code using try & catch:

复制代码
const getPort = () => {
  try {
    const file = fs.readFileSync('config.json');
    const c = JSON.parse(file);
    return c.port;
  } catch(e) {
    return 3000;
  }
}
复制代码

 

And now, we want to use Either to rewirte the code:

复制代码
// SETUP: fake fs
//==========
const fs = {
  readFileSync: name => {
    if(name === 'config.json') {
      return JSON.stringify({port: 8888})
    } else {
      throw('missing file!')
    }
  }
}

//=================

const Right = x => ({
    map: f => Right(f(x)),
    fold: (f, g) => g(x),
    toString: () => `Right(${x})`
  });

const Left = x => ({
  map: f => Left(x),
  fold: (f, g) => f(x),
  toString: () => `Left(${x})`
});

const fromNullable = x => 
  x != null ? Right(x): Left(null);

const tryCatch = f => {
  try {
    return Right(f());
  } catch(e) {
    return Left(e);
  }
}

//=========================
const getPort = () =>
  tryCatch(() => fs.readFileSync('config.json'))
  .map(f => JSON.parse(f))
  .fold(
    x => 3000,
    x => x.port);

console.log(getPort('config.json'))
复制代码

 

We wrote the function 'tryCatch', the idea is put the code need to be checked in try, when success call 'Right', error, call 'Left()'.

tryCatch(() => fs.readFileSync('config.json'))

Read the file, is success, will return file content. If not, then goes to set default 3000.

  .fold(
    x => 3000,
    x => x.port);

 

It works, but we still miss one things, in the old code, the 'JSON.parse' are also wrapped into try catch.

const getPort = () =>
  tryCatch(() => fs.readFileSync('config.json')) //Right('{port:8888}')
  .map(f => tryCatach(() => JSON.parse(f))) //Right(Right({port:8888}))

But once we also wrap parseing code into tryCatch function, the return value is 2d-Right. So we want to flatten it.

 

复制代码
const Right = x => ({
    map: f => Right(f(x)),
    flatMap: f => f(x),
    fold: (f, g) => g(x),
    toString: () => `Right(${x})`
  });

const Left = x => ({
  map: f => Left(x),
  flatMap: f => f(x),
  fold: (f, g) => f(x),
  toString: () => `Left(${x})`
});
复制代码

We add 'flatMap', so instead of putting the value into Right() or Left(), we just return the value. Because we know the value passed in is already a Right or Left.

 

const getPort = () =>
  tryCatch(() => fs.readFileSync('config.json')) //Right('{port:8888}')
  .flatMap(f => tryCatch(() => JSON.parse(f))) //Right({port:8888})
  .fold(
    x => 3000,
    x => x.port);

 

 

---------

复制代码
// SETUP: fake fs
//==========
const fs = {
  readFileSync: name => {
    if(name === 'config.json') {
      return JSON.stringify({port: 8888})
    } else {
      throw('missing file!')
    }
  }
}

//=================

const Right = x => ({
    map: f => Right(f(x)),
    flatMap: f => f(x),
    fold: (f, g) => g(x),
    toString: () => `Right(${x})`
  });

const Left = x => ({
  map: f => Left(x),
  flatMap: f => f(x),
  fold: (f, g) => f(x),
  toString: () => `Left(${x})`
});

const fromNullable = x => 
  x != null ? Right(x): Left(null);

const tryCatch = f => {
  try {
    return Right(f());
  } catch(e) {
    return Left(e);
  }
}

//=========================
const getPort = () =>
  tryCatch(() => fs.readFileSync('config.json')) //Right({port:8888})
  .flatMap(f => tryCatch(() => JSON.parse(f))) //Right(Right({port:8888}))
  .fold(
    x => 3000,
    x => x.port);

console.log(getPort('config.json'))
复制代码

 

-----

You can also rename 'flatMap' to 'chain'. Sometime 'flatMap' or 'chain' looks similar to 'fold' implementation. But the meaning is different, here 'chain / flatMap' says It says, "If we're going to return another Either, we are going to use chain instead of map." 'fold' says just get the value out of the box, it's done!

posted @   Zhentiw  阅读(359)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-02-19 [Angular] Difference between ngAfterViewInit and ngAfterContentInit
2017-02-19 [Angular] Difference between ViewChild and ContentChild
2017-02-19 [Angular] @ContentChildren and QueryList
2017-02-19 [Angular] @ContentChild and ngAfterContentInit
2017-02-19 [Angular] Content Projection with ng-content
2016-02-19 [Immutable + AngularJS] Use Immutable .List() for Angular array
2016-02-19 [Protractor] Running tests on multiple browsers
点击右上角即可分享
微信分享提示