本文介绍了TypeScript中的注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出一种在TypeScript中美化Monadic库的方法.尽管monad本身的实现进展顺利,但其用法看起来像是熟悉的回调地狱.

I am trying to figure out a way to prettify monadic libraries in TypeScript. While the implementation of the monad itself goes pleasantly ahead, its usage looks like the familiar callback hell.

我想知道是否有办法劫持async/await或yield/for..of的单子语法糖,但是我必须承认我在连接点时遇到了一些麻烦.是否可以在既不是Promise也不是Iterable的事物上使用这些构造,并且该构造与由react组件组成的延续monad一样不同?

I was wondering if there is a way to hijack the existing monadic syntactic sugar of async/await or yield/for..of, but I must admit I am having some trouble connecting the dots. Is it possible to use these constructs on something that is neither a Promise nor an Iterable, and is as different as a continuation monad composed with react components?

推荐答案

我受时间限制,但这里有一个简短的小示例,使用延续monad Cont 作为示例

I'm limited on time but here's a quick little example using the continuation monad Cont as an example

// 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 -表示法- do 是JS中的保留关键字,因此我将函数命名为 run

Now the same thing using a sort of do-notation – do is a reserved keyword in JS, so I named my function 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

警告::您可以使用 async/await ,但随后您的价值观陷入了承诺"之内–在大多数情况下,这很烦人

warning: You could use async/await but then your values get stuck inside of Promises – that'd probably annoying under most circumstances.

这篇关于TypeScript中的注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 03:46