我正在撰写一系列函数,但我想知道实现我想要的最好方法是什么,这就是我的编写方式:
const composeP = (...fns) => fns.reduce((f, g) => async (...args) => f(await g(...args)))
const profileSummary = profileData => composeP(createProfileSummary, getMKAProfile)(profileData)
现在我想要的是检查一下,如果我输入的profileData是某个字符串,例如" cantbesearched"我想立即将值返回到" profileSummary"变量而不是执行以前的函数...
因此可以创建一个" filterWords"功能,把它放在这样的构图前面:
const profileSummary = profileData => composeP(createProfileSummary, getMKAProfile, filterWords)(profileData)
如果检测到某些单词,则跳过左侧的前一个函数然后返回一个值。
答案 0 :(得分:0)
Is it possible to create a "filterWords" function to be put it in front of the composition?
No. What you want to do is branching, which is not possible with function composition.
What you can do is compose functions that work on a type which provides an error path, like Maybe
or Either
. (You can also consider exceptions as a builtin error path for every type, so just throw
).
Oh wait, you already are doing that! You didn't write a plain function composition compose
, you wrote composeP
which uses monadic Kleisli composition - and promises do have such an error path:
function filterWords(word) {
return word == "cantbesearched"
? Promise.reject(new Error("filtered for your safety"))
: Promise.resolve(word);
}