代码之家  ›  专栏  ›  技术社区  ›  3Dos

在ramda中使用fetchapi

  •  4
  • 3Dos  · 技术社区  · 6 年前

    我正在学习Ramda并尝试实现无点编程。为了做到这一点,我试着在这里和那里重构,但被困在这个。

    我显然认为这不起作用,因为调用是异步的,但我找不到这个代码有什么问题。

    // Why is this
    const toJSONRamda = R.pipe(
      R.prop('json'), // getting the 'json' function
      R.call // and calling it
    )
    
    // different from this
    const toJSON = response => response.json()
    
    // Works
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(toJSON)
      .then(console.log)
      
    // Does not Work
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(toJSONRamda)
      .then(console.log)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
    1 回复  |  直到 6 年前
        1
  •  10
  •   Scott Sauyet    6 年前

    这不起作用的原因是 json 响应对象的方法不是纯函数。这真是一种方法。当你使用 pipe(prop('json'), call) json文件 方法实际使用 this . 拉姆达的 call 对象。

    有一个拉姆达替代方案:

    const toJSONRamda = R.invoker(0, 'json')
    
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(toJSONRamda)
      .then(console.log)
    <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

    invoker 使用方法。这些应该有助于描述其工作原理:

    R.invoker(0, 'method')(obj) = obj['method']()
    R.invoker(1, 'method')(a, obj) = obj['method'](a)
    R.invoker(2, 'method')(a, b, obj) = obj['method'](a, b)
    //...
    

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(resp => resp.json())
      .then(console.log)
    

    如果这只是一个学习练习,那么,无论如何,请尝试把它变成一个无点的版本。但我会留下它,因为它是生产代码。