Ramda通过链调用传递"可能"错误消息

alt*_*han 2 javascript functional-programming ramda.js fantasyland ramda-fantasy

假设我有一堆函数返回Just或Nothing值,我想将它们链接在一起;

var a = M.Just("5").map(function(data){
    return 1;
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Just(2);
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Nothing("Reason 1");
}).chain(function(data){
/*Make some operation return Just or Nothing */
    console.log(data);
    return M.Nothing("Reason 2");
}).getOrElse(function(data){
    console.log(data);
    return "Message";
});

console.log(a());
Run Code Online (Sandbox Code Playgroud)

输出:

>     1
>     2
>     undefined
>     Message
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,因为它在函数返回M.Nothing("Reason 1")的步骤失败,所以它没有通过我预期的其他函数.我相信Nothing没有有效的构造函数来获取参数.有没有办法在执行结束时获取此失败消息?我在民间故事中也试过这个,它与梦幻土地规格有关吗?

谢谢

小智 5

您可以使用Either monad用于此目的,如文档中所述.

Either类型与Maybe类型非常相似,因为它通常用于以某种方式表示失败的概念.

我修改了你给下面的Either monad的例子.

var R = require('ramda');
var M = require('ramda-fantasy').Either;

var a = M.Right("5").map(function(data){
return 1;
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Right(2);
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Left("Reason 1");
}).chain(function(data){
/*Make some operation return Just or Nothing */
console.log(data);
return M.Left("Reason 2");
});
console.log(a);
console.log(a.isLeft);
Run Code Online (Sandbox Code Playgroud)