我有一个案例,我有一个可以很好地组合在一起的管道,但在一个实例中,我需要触发对我无法控制的 API 的异步调用。我不一定关心结果,只关心它是否成功,然后想继续将 arg 传递给该调用(而不是返回值)。所以我的管道看起来像这样:
const extractUserIdFromResponse = R.andThen( R.prop( user_id ) );
const callExternalApi = tryCatch(
doApiCall,
handleAPIFailure
);
const pipeline = R.pipe(
getRecordFromDatabase,
extractUserIdFromResponse,
callExternalApi,
doSomethingElseWithUserId
);
基本上,我希望 doSomethingElseWithUserId 函数显然接受 userId
作为参数,而不是从 callExternalApi
返回的结果。我对此有点陌生,所以我不确定我是否走在正确的轨道上。
预先感谢您的帮助!
最佳答案
我也是 ramda 的新手,这就是为什么我不确定答案的准确性,但是doSomethingElseWithUserId
可以收到user_id
来自getRecordFromDatabase
通过callExternalApi
.
<强> https://codesandbox.io/s/affectionate-oskar-kzn8d
import R from "ramda";
const getRecordFromDatabase = () => (
new Promise((resolve, reject) => {
return resolve({ user_id: 42 });
})
);
// I assume that you need to pass the arg here in handleAPIFailure as well
const handleAPIFailure = () => {};
const doApiCall = args => (
new Promise((resolve, reject) => {
return resolve(args);
})
);
const extractUserIdFromResponse = R.andThen(R.prop("user_id"));
const callExternalApi = R.tryCatch(doApiCall, handleAPIFailure);
const doSomethingElseWithUserId = user_id => {
console.log(user_id); // 42
};
const pipeline = R.pipe(
getRecordFromDatabase,
extractUserIdFromResponse,
callExternalApi,
R.andThen(doSomethingElseWithUserId)
);
pipeline();
关于javascript - 从复合函数中的上一个函数访问 Arg(使用 Ramda.pipe),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60344745/