Ramda - andThen, otherwise, andFinally?

737 Views Asked by At

Is there a 'finally' implementation in Ramda, for doing functional composition, and invoking a function regardless of the outcome of a promise? I want to to something like this:

compose(
    finally(() => console.log("The promise resolved or rejected, who cares!"))
    fetchAsync(id)
)

if not i was thinking about doing something like this:

const finally = fn => compose(
        otherwise(() => fn()),
        andThen(() => fn())
);

Any thoughts on this?

2

There are 2 best solutions below

2
On

An andThen call after otherwise would be called no matter the outcome, and can act as finally:

compose(
  andThen(() => console.log("The promise resolved or rejected, who cares!")),
  otherwise(() => console.log('failed')),
  fetchAsync(id)
)
1
On

I don't think otherwise is sufficient in this case, because it's only called on-failure. By contrast, .finally is called no matter what -

const effect = f => x =>
  (f(x), x)
  
const log = label =>
  effect(x => console.log(label, x))
  
const err = label =>
  effect(x => console.error(label, x))

const test = p =>
  p
  .then(log("resolved"))
  .catch(err("rejected"))
  .finally(log("you will ALWAYS see this"))

test(Promise.resolve(1))
test(Promise.reject(2))

resolved 1
Error: rejected 2
you will ALWAYS see this undefined
you will ALWAYS see this undefined

I'm not sure if Ramda has such a function in its library. If not, it's easy to implement -

const andFinally =
  curry(function(f, p){ return p.finally(f) })