Skip to content

Pipeline operator -> syntax sugar for Promise.then? #189

Description

@simov

TBH I haven't read through all of the proposals, issues, and comments, so excuse me for that, but for the past 3 years I've been using this little helper:

var compose = (...fns) => (args) =>
  fns.reduce((p, f) => p.then(f), Promise.resolve(args))

and I've always thought that the pipeline operator should be merely a syntax sugar for Promise.then.

That's how I've built my own http client, and also used it in many other projects, but here is an example of a bigger pipeline as well.

So again I've always thought that the pipeline operator should only be helping me with getting rid of the initial step of composing the pipeline:

var {res, body} = await compose(
  Request.defaults({headers: {'user-agent': 'request-compose'}}),
  Request.url('https://api.github.com/users/simov'),
  Request.send(),
  Response.buffer(),
  Response.string(),
  Response.parse(),
)()

and thus make it as:

var {res, body} = await
     Request.defaults({headers: {'user-agent': 'request-compose'}})
  |> Request.url('https://api.github.com/users/simov')
  |> Request.send()
  |> Response.buffer()
  |> Response.string()
  |> Response.parse()

similar to what was done for Promises and async/await back then.

Partial application and having to await things there is not a problem:

var sum = compose(
  (x) => x + 1,
  (x) => new Promise((resolve) => setTimeout(() => resolve(x + 2), 1000)),
  (x) => x + 3,
  async (x) => (await x) + 4
)
await sum(5) // 15 (after one second)

because things are being awaited always:

var sum = await 5 // 15 (after one second)
  |> (x) => x + 1
  |> (x) => new Promise((resolve) => setTimeout(() => resolve(x + 2), 1000))
  |> (x) => x + 3
  |> async (x) => (await x) + 4

which is the only downside, but unless you are chaining thousands of Promises it's fine.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions