2

I have this code:

const compose2 = (f, g) => (...args) => f(g(...args))
const compose = (...fns) => fns.reduce(compose2)

const count = arr => arr.length
const split = str => str.split(/\s+/)
const addAsyncWord = async str => `${str} some words obtained asynchronously`
const read = text => text


const word = compose(
        count,
        split,
        (await addAsyncWord),
        read
    )

console.log('word ->', await word()) //<- edited

but is throwing the following error:

Uncaught SyntaxError: missing ) in parenthetical

output expected after reading, concat words (obtained from a server randomly, needs to be asynchronously), spliting words, and finally count the total length, must be something similar to this:

word -> 10

How to make this to work? thanks

4
  • 1
    From a purely functional agnle you can't. Function composition is based on a functor (of the function type). If you have to deal with async functions you need another type, namely continuations and the appropriate tools to compose them (applicative and monad). Commented Nov 20, 2021 at 21:46
  • 2
    Take a look at ramda implementation of composeWith and andThen: github.com/ramda/ramda/blob/master/source Commented Nov 20, 2021 at 22:13
  • 1
    I'm not getting a syntax error from your code? But word is a function that you never call… Commented Nov 21, 2021 at 0:37
  • 5
    You'll need const compose2 = (f, g) => async (...args) => f(await g(...args)). An await in the arguments list of compose won't achieve anything, addAsyncWord is a function not a promise that can be waited for. Commented Nov 21, 2021 at 0:39

1 Answer 1

4

I will post my solution here if helps anyone in the future:

const compose2 = (f, g) => async (...args) => f(await g(...args))
const compose = (...fns) => fns.reduce(compose2)

const count = arr => arr.length
const split = str => str.split(/\s+/)
const addAsyncWord = async str => `${str} some words obtained asynchronously`
const read = text => text

const word = compose(
    count,
    split,
    addAsyncWord,
    read
)

const test = async () => {
    const word1 = await word('Hello world')
    console.log('word ->', word1)
}

test()

thank you for your comments.

Sign up to request clarification or add additional context in comments.

1 Comment

if you have more than one argument it could be rewrited as const compose2 = (f, g) => async (...args) => f(...await g(...args))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.