如何将 R.cond
与 promises 一起使用?
像这样的..
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>
最佳答案
我认为这就是您所追求的,通过将其与 testStatus
组合在一起,您应该能够获得 response
对象并执行条件分支。
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>
关于javascript - 在 Ramda 中有条件地 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46591217/