【问题标题】:Javascript - how to compose asynchronous functionsJavascript - 如何编写异步函数
【发布时间】:2021-12-31 02:56:53
【问题描述】:

我有这个代码:

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

但抛出以下错误:

Uncaught SyntaxError: missing ) in parenthetical

读取后预期的输出,concat words(从服务器随机获取,需要异步),split words,最后计算总长度,一定是这样的:

word -> 10

如何使它工作?谢谢

【问题讨论】:

  • 从纯粹的功能性角度来说,你不能。函数组合基于函子(函数类型)。如果您必须处理异步函数,则需要另一种类型,即延续和组合它们的适当工具(应用程序和 monad)。
  • 看看composeWithandThen的ramda实现:github.com/ramda/ramda/blob/master/source
  • 您的代码没有出现语法错误?但是word 是一个你永远不会调用的函数……
  • 您需要const compose2 = (f, g) =&gt; async (...args) =&gt; f(await g(...args))compose 的参数列表中的 await 不会实现任何目标,addAsyncWord 是一个函数,而不是可以等待的承诺。

标签: javascript asynchronous functional-programming


【解决方案1】:

如果将来对任何人有帮助,我会在这里发布我的解决方案:

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()

感谢您的 cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多