RamdaJS-如何使用带有同步和异步功能的管道?

时间:2019-09-08 02:11:30

标签: ramda.js

我正在尝试学习Ramda,以及如何在日常工作中使用它。所以我有一个简短的问题。 “如何使用带有同步和异步功能的管道?”还是最好的,我该如何改善以下代码?

const AuthService = () => ({
  async signIn(credentials: Credentials): Promise<AuthSession> {
    const result = await api.signIn(credentials)

    return R.pipe(
      signInResultToAuthSession,
      saveAuthSession
    )(result)
  }
})

[编辑]:我认为更好的第二种选择。

const AuthService = () => ({
  async signIn(credentials: Credentials): Promise<AuthSession> {
    return api.signIn(credentials).then(
      R.pipe(
        signInResultToAuthSession,
        saveAuthSession
      )
    )
  }
})

2 个答案:

答案 0 :(得分:1)

您可以创建如下函数:

web.config

然后您的管道如下所示:

<rewrite>
<rules>
<rule name="service" stopProcessing="true">
<match url="^service/([0-9]+)" />
<action type="Rewrite" url="service-details.php?id={R:1}" />
</rule>
</rules>
</rewrite>

您甚至可以通过以下方式捕获异常:

const then = f => p => p.then(f)
const AuthService = () => ({
  async signIn(credentials: Credentials): Promise<AuthSession> {
    return R.pipe(
      api.signIn,
      then(signInResultToAuthSession),
      then(saveAuthSession),
    )(credentials)
  }
})

答案 1 :(得分:1)

仅在这种情况下添加了

pipeWith。它将功能包装在一个通用接口(此处为then)中,并像pipe一样传递结果。

const api = {signIn: ({pwd, ...creds}) => Promise.resolve({...creds, signedIn: true})}
const signInResultToAuthSession = (creds) => Promise.resolve({...creds, auth: true})
const saveAuthSession = (creds) => Promise.resolve({...creds, saved: true})

const AuthService = {
  signIn: pipeWith(then)([
    api.signIn, // [1]
    signInResultToAuthSession,
    saveAuthSession
  ])
}

AuthService.signIn({name: 'fred', pwd: 'flintstone'})
  .then(console.log)

// [1]: `bind` might be necessary here, depending on the design of `api.signIn`
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script>const {pipeWith, then} = R                                   </script>

请注意,pipeWith将函数包装在数组中。有一天,我们想对pipe做同样的事情,但这是一个巨大的突破。