简体   繁体   中英

Ramda Pass “Maybe” Error Message Through Chain Calls

Lets say I have bunch of functions returns Just or Nothing values and I want to chain them together like this;

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());

Output:

>     1
>     2
>     undefined
>     Message

In this above code since it is failing at step where function returns M.Nothing("Reason 1") it does not go through over other functions which is what I expected. I believe there is no valid constructor for Nothing that takes parameters. Is there a way to get this failure message at the end of the execution ? I have tried this in folktale as-well, does it related with fantasy land spec?

Thanks

You can use Either monad for this purpose as it is stated in docs.

The Either type is very similar to the Maybe type, in that it is often used to represent the notion of failure in some way.

I modified the example you gave with Either monad below.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM