我有一根这样的烟斗
const asyncFn = (x) => {
return Future.tryP(() => Promise.resolve(x + ' str2'))
};
const pipeResult = S.pipe([
x => S.Right(x + " str1"), // some validation function
S.map(asyncFn),
])("X");
pipeResult.fork(console.error, console.log);我想在asyncFn中做一些异步操作。问题是,当我有Right作为输入时,我可以更多地派生它。
当我登录pipeResult时,我看到以下内容:
Right (tryP(() => Promise.resolve(x + ' str2')))我该怎么做呢?
发布于 2019-11-05 18:33:18
Either a b和Future a b都能够表示失败/成功。在处理异步计算时,使用Future a b通常比使用Future a (Either b c)更好。更简单、更扁平的类型需要较少的映射:S.map (f)而不是S.map (S.map (f))。另一个优点是错误值总是在同一位置,而使用Future a (Either b c)时,a和b都表示失败的计算。
不过,我们可能已经有了一个验证函数,它返回一个或多个。例如:
// validateEmail :: String -> Either String String
const validateEmail = s =>
s.includes ('@') ? S.Right (S.trim (s)) : S.Left ('Invalid email address');如果我们有一个Future String String类型的值fut,我们如何验证fut可能包含的电子邮件地址?首先要尝试的始终是S.map
S.map (validateEmail) (fut) :: Future String (Either String String)如果能避免这种嵌套就好了。为此,我们首先需要定义一个从Either a b到Future a b的函数
// eitherToFuture :: Either a b -> Future a b
const eitherToFuture = S.either (Future.reject) (Future.resolve);我们现在可以将一个任一返回函数转换为一个未来返回函数:
S.compose (eitherToFuture) (validateEmail) :: String -> Future String String让我们回顾一下S.map的用法
S.map (S.compose (eitherToFuture) (validateEmail)) (fut) :: Future String (Future String String)我们仍然有嵌套,但是现在内部和外部类型都是Future String _。这意味着我们可以用S.chain替换S.map,以避免引入嵌套:
S.chain (S.compose (eitherToFuture) (validateEmail)) (fut) :: Future String Stringhttps://stackoverflow.com/questions/58706276
复制相似问题