首页 文章

TypeScript中的标记

提问于
浏览
0

我试图想出一种在TypeScript中美化monadic库的方法 . 虽然monad本身的实现令人愉快,但它的使用看起来像熟悉的回调地狱 .

我想知道是否有办法劫持async / await或yield / for..of现有的monadic语法糖,但我必须承认我在连接点时遇到一些麻烦 . 是否可以在既不是Promise也不是Iterable的东西上使用这些结构,并且与使用react组件组成的continuation monad不同?

1 回答

  • 2

    我是一个使用continuation monad Cont 作为示例的快速小例子

    // first: WITHOUT do-notation
    
    const Cont = f => ({
      runCont: f,
      chain: g =>
        Cont(k => f (x => g (x) .runCont (k)))
    })
    
    Cont.of = x =>
      Cont(k => k (x))
    
    const result = Cont.of (2) .chain (x =>
      Cont.of (3) .chain (y =>
        Cont.of (x + y)))
    
    result.runCont (console.log)
    // 5
    

    现在同样的事情使用 do -notation - do 是JS中的保留关键字,所以我将我的函数命名为 run

    // second: WITH do-notation
    
    const run = g => {
      const next = x => {
        let {value, done} = g.next (x)
        return done
          ? value
          : value.chain (next)
      }
      return next (null)
    }
    
    const Cont = f => ({
      runCont: f,
      chain: g =>
        Cont(k => f (x => g (x) .runCont (k)))
    })
    
    Cont.of = x =>
      Cont(k => k (x))
    
    const result = run (function* () {
      let x = yield Cont.of (2)
      let y = yield Cont.of (3)
      return Cont.of (x + y)
    } ())
    
    result.runCont (console.log)
    // 5
    

    warning: 你可以使用 async/await 然后你的 Value 卡在Promises内 - 这在大多数情况下可能很烦人 .

相关问题