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

问题描述 投票:0回答:1

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

谢谢您的帮助!

javascript functional-programming ramda.js
1个回答
0
投票

我也是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();
© www.soinside.com 2019 - 2024. All rights reserved.