使用带有ramda的fetch api

3Do*_*Dos 5 javascript functional-programming promise ramda.js fetch-api

我正在学习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)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

Sco*_*yet 9

这不起作用的原因是json响应对象的方法不是纯函数.这真的是一种方法.当您使用时pipe(prop('json'), call),您试图将该方法称为纯函数.在某些情况下,这将有效.但在这里,该json方法实际上使用this.Ramda's call不提供任何this物品.

有一个Ramda替代方案:

const toJSONRamda = R.invoker(0, 'json')

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(toJSONRamda)
  .then(console.log)
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
Run Code Online (Sandbox Code Playgroud)

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)
//...
Run Code Online (Sandbox Code Playgroud)

但是,有一点不容错过.无点编程只有在提高可读性的情况下才有用.这对我来说已经很完美了:

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

如果这只是一个学习练习,那么,请务必尝试将其转换为无点版本.但是我会把它留给生产代码.