简体   繁体   English

使用带有ramda的fetch api

[英]using the fetch api with ramda

I'm learning Ramda and try to reach pointfree programming. 我正在学习Ramda并试图达到无点编程。 In order to do that, I try to refactor here and there but got stuck on this. 为了做到这一点,我尝试在这里和那里进行重构但是却坚持这一点。

I obviously think this doesn't work because the call is asychronous but I could not find what is wrong with this code. 我显然认为这不起作用,因为调用是异步的,但我找不到这个代码有什么问题。

 // 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> 

The reason this doesn't work is that the json method of the response object is not a pure function. 这不起作用的原因是响应对象的json方法不是纯函数。 It is really a method. 这真的是一种方法。 When you use pipe(prop('json'), call) , you are trying to call that method as a pure function. 当你使用pipe(prop('json'), call) ,你试图将该方法称为纯函数。 In some circumstances that will work. 在某些情况下,这将有效。 But here, the json method actually uses this . 但是在这里, json方法实际上使用了this Ramda's call does not supply any this object. 拉姆达的call不提供任何this物件。

There is a Ramda alternative: 有一个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 works with methods. invoker使用方法。 These should help describe how it works: 这些应该有助于描述它的工作原理:

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)
//...

However, there is an important point not to miss. 但是,有一点不容错过。 Point-free programming is useful only so long as it improves readability. 无点编程只有在提高可读性的情况下才有用。 This to me is already perfectly readable: 这对我来说已经很完美了:

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

If this is only a learning exercise, then, by all means feel free to try to turn that into a point-free version. 如果这只是一个学习练习,那么,请务必尝试将其转换为无点版本。 But I would leave it as is for production code. 但是我会把它留给生产代码。

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

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