(使用Rambda.pipe)从组合函数中的上一个函数访问Arg

时间:2020-02-21 18:58:12

标签: javascript functional-programming ramda.js

在某些情况下,我的管道可以很好地组合在一起,但是在某些情况下,我需要触发对我无法控制的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作为arg,而不是callExternalApi返回的结果。我对此有些陌生,因此不确定我是否在正确的轨道上。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我也是ramda的新手,这就是为什么我不确定答案的准确性,但是doSomethingElseWithUserId可以从user_idgetRecordFromDatabase接收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();