微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

拉姆达-然后,否则,最后?

如何解决拉姆达-然后,否则,最后?

Ramda中是否有一个“最终”实现,可以进行功能组合和调用功能,而与承诺的结果无关?我想要这样的事情:

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

如果不是,我正在考虑做这样的事情:

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

对此有何想法?

解决方法

andThen之后的otherwise调用无论结果如何都将被调用,并且可以充当finally

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

在这种情况下,我认为otherwise是不够的,因为它仅称为on-failure。相比之下,.finally无论如何都被称为-

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

我不确定Ramda在其库中是否具有这样的功能。如果没有,那么很容易实现-

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。