0

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?

ruckk
  • 15
  • 5

2 Answers2

0

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)
)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • I see, but then i would be required to have an otherwise also. I would just want to have one function after the async one. – ruckk Sep 29 '20 at 15:47
  • There's also the concerns raised in this thread https://stackoverflow.com/questions/35999072/what-is-the-equivalent-of-bluebird-promise-finally-in-native-es6-promises – ruckk Oct 06 '20 at 16:04
0

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) })
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Yea I guess this is a better way of doing it. But it requires that the promise implementation used supports finally (which is not always the case). – ruckk Oct 06 '20 at 16:07