2017-10-05 4 views
1

약속과 함께 R.cond을 어떻게 사용할 수 있습니까? 이 같은RamDA에서 조건부로 조건부

뭔가 ..

const fetchBin = (url) => fetch(`https://httpbin.org${url}`).then((response) => { 
 
    var contentType = response.headers.get("content-type"); 
 
    if(contentType && contentType.includes("application/json")) { 
 
     return response.json(); 
 
    } 
 
    throw new TypeError("Oops, we haven't got JSON!"); 
 
}) 
 

 
const testStatus = (status) => fetchBin(`/status/${status}`); 
 

 
const isOk = R.propEq('statusCode', 200); 
 
const testCond = R.cond([ 
 
    [ R.pipeP(testStatus, isOk), (resp) => console.log('The resp is ', resp) ], 
 
    [ R.T, (code) => console.log('The resp is NOT ok', code) ] 
 
]) 
 

 
testCond(404) 
 
// R.pipeP(testStatus, isOk)(404)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

+0

나는'test'의'then' 안에'testStatus'를 넣어야한다고 생각합니다. 왜냐하면 Ramda 문서에 따르면, 술어는'cond'의 순수한 함수라고 가정하기 때문입니다. –

답변

2

나는 이것이 당신이 response 개체를 얻을 수와 조건 분기를해야 testStatus로를 구성하여, 이후에 무슨 생각 .

const fetchBin = (url) => fetch(`https://httpbin.org${url}`).then((response) => { 
 
    var contentType = response.headers.get("content-type"); 
 
    if(contentType && contentType.includes("application/json")) { 
 
     return response.json(); 
 
    } 
 
    throw new TypeError("Oops, we haven't got JSON!"); 
 
}) 
 

 
const testStatus = (status) => fetchBin(`/status/${status}`); 
 

 
const isOk = R.propEq('statusCode', 200); 
 
const testCond = R.pipeP(testStatus, R.cond([ 
 
    [isOk, resp => console.log('The resp is OK :' + resp.statusCode)], 
 
    [R.T, resp => console.log('The resp is NOT OK :' + resp.statusCode)] 
 
])); 
 

 
testCond(404) 
 
// R.pipeP(testStatus, isOk)(404)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

+0

안녕하세요 @ MinusFour, 나는 당신의 제안을 시도했지만 작동하지 않았다. 'R.pipeP (testStatus,/* 약속이 해결되지 않은 경우 (이 경우 catch) 조건은 실행되지 않습니다. * /)' [여기] (https://runkit.com/ridermansb)에서 확인할 수 있습니다./ramda-promises) – ridermansb

+1

catch 절에 의존한다면 다소 문제가 될 것입니다. 거부하더라도 약속을 이행해야합니다. 400 개의 상태 코드에 대해서도 400 개의 상태 코드 속성을 가진 JSON 응답을 반환한다는 인상을 받았습니다. – MinusFour

2

신선한 관점 주변

우리가 우리의 프로그래밍 언어를 굽힘 사람이 될 것을 자신을 생각 나게하는 좋은 아닌 다른 방법

내가 너를 때리고있는 것처럼 보인다. 잘못된 경로. fetchBin은 우리가 실제로 찾고있는 사람의 밀짚 맨입니다. 우리는 URL을 취하고 구문 분석 된 JSON 응답을 반환하는 함수가 필요합니다. fetchJSON

이 거기에서, 우리는 fetchJSON를 사용하여 fetchBin를 구현의이 사람 부르 자 - 자원이 404 상태 나 잘못된 콘텐츠 형식과 200 상태를 반환 여부를 중요하지 않습니다 (아래의 XML 예제 참조) - 어느 쪽이든 약속은 오류 처리기 (console.error 아래, 대신에 .then(console.log).catch(console.error))로 올바르게 라우팅됩니다. 여기에 요점이 명확하지 않은 경우를 위해 fetchBin은 HTTP 상태 코드 또는 세부 사항과 같은 세부 정보와 관련이 없어야합니다. 응답의 Content-Type 헤더는 파싱 된 JSON을 요청하고 나머지에 대해 걱정하지 말 것입니다.

이것을 공유하는 이유는 특정 사고 방식에 얽매이지 않도록 돕는 것입니다. R.cond은 꽤 입니다. 폼입니다. 우리가 완벽하게 솔직 해지면 프로그램 포크의 의미를 배열에서 감추고 프로그램에서 결코 사용할 수없는 조건부 브랜치를 저장하는 썽크를 만들어야합니다. true 게으름은 if/else 또는 ?:을 사용하여 엄격하게 평가 된 JavaScript에서만 사용할 수 있습니다. 여하튼, 우리는 심지어 R.pipe, 또는 R.pipeP, 또는 R 전혀 필요 최대 끝나지 않았다 - 그들없이 당신은 여전히 ​​우리가 R.cond 같은 단단한 양식에서 자신을 바인딩 해제되면

상황이 자연스럽게 함께 맞는 불필요한 작업을하고 있습니다. ..

const fetchJSON = url => 
 
    fetch (url) 
 
    .then (responseOK) 
 
    .then (parseJSON) 
 

 
const responseOK = (response) => 
 
    { 
 
    if (response.status >= 200 && response.status < 300) 
 
     return response 
 
    else 
 
     throw Object.assign (Error (response.statusText), { response }) 
 
    } 
 

 
const parseJSON = response => 
 
    response.json() 
 
    
 
const fetchBin = (url) => 
 
    fetchJSON ('https://httpbin.org' + url) 
 

 
fetchBin ('/anything?a=b') .then (console.log, console.error) 
 
// all things good ! 
 
// => { args: {a: 'b'}, data: '' ... } 
 

 
fetchBin ('/status/404') .then (console.log, console.error) 
 
// non-200 status goes to error handler 
 
// => { Error: NOT FOUND ..., response } 
 

 
fetchBin ('/xml') .then (console.log, console.error) 
 
// bad JSON goes to error handler 
 
// => SyntaxError: Unexpected token < in JSON at position 0


좋아, 그래서 우리가이 R하지만이 대답을 필요로하지 않았다 그것을 일반적으로 경험할 수있는 의미로 암시하는 것은 아닙니다.Ramda는 훌륭한 도구이며 함수형 프로그래밍에 대해 많은 것을 가르쳐 줄 수 있습니다 - 때로는 뒤로 물러나고 프로그램이 어떤 식으로 표현 될 수 있는지 평가하는 것을 기억하십시오 원하는 언어 (또는 라이브러리, 또는 function; R.cond) want