javascript - 在 Ramda 中有条件地 promise

标签 javascript functional-programming promise ramda.js

如何将 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/

相关文章:

javascript - 将十进制数的输出限制为特定精度

functional-programming - 为什么有一个函数未定义的消息,而它是关于变量的

javascript - Monad的功能组合…不起作用

javascript - 外部 JavaScript 文件已连接,但某些代码无法正常工作

javascript - 这个函数的运行时复杂度是多少?

javascript - JS promise : Fulfill vs Resolve

javascript - 使用 Promises 等待嵌套的异步任务

javascript - 如何使用express在nodejs中执行promise

javascript - 如何确保 Google Analytics 在调用其函数之前已加载?

f# - 功能响应式(Reactive) F# - 在游戏中存储状态