繁体   English   中英

使用带有ramda的fetch api

[英]using the fetch api with ramda

我正在学习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> 

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

有一个Ramda替代方案:

 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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM