簡體   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