javascript - Promise.all 位于带有 FP promise 的对象数组上

标签 javascript node.js functional-programming ramda.js

所以,我正在使用 NodeJS 和 Ramda,并且我有一个对象数组,例如:

[
    {
        x: 'abc',
        y: []
    },
    {
        x: '123',
        y: [1, 2, 3]
    }
]

然后我想在返回 promise 的请求中使用 x ,结果是这样的(使用 Ramda 的 overlensProp ):

[
    {
        x: Promise<String>,
        y: []
    },
    {
        x: Promise<String>,
        y: [1, 2, 3]
    }
]

现在我想把最后一个数组变成这样:

Promise<[
    {
        x: String,
        y: []
    },
    {
        x: String,
        y: [1, 2, 3]
    }
]>

我怎样才能以函数式方式实现这一点(如函数式编程,而不是仅仅起作用的东西=])?

我能想到的最好的方法是从 x 获取所有 promise ,使用 Promise.all 并使用 then使用 y 压缩 结果。但我不接受这种解决方案。

最佳答案

一种选择是引入一个新的辅助函数,其行为类似于专门用于 Promises 的 R.traverse,并将处理对象的特定属性。我们称之为traversePropP:

// traversePropP :: (a -> Promise b) -> String -> {a|...} -> Promise {b|...}
const traversePropP = R.curry((toPromiseFn, prop, obj) =>
  toPromiseFn(obj[prop]).then(v => R.assoc(prop, v, obj)))

这可以有效地让您从对象的指定属性生成 Promise,并用创建的 Promise 解析的最终值替换该属性。

然后,您可以使用这个新函数来映射数组中的所有对象,然后将生成的 Promise 数组传递给 Promise.all

const traversePropP = R.curry((toPromiseFn, prop, obj) =>
  toPromiseFn(obj[prop]).then(v => R.assoc(prop, v, obj)))

// example Promise-producing function that delays a value
const delayP = n => x =>
  new Promise((res, rej) => setTimeout(() => res(x), n))

const fn = R.pipe(
  R.map(traversePropP(delayP(500), 'x')),
  x => Promise.all(x)
)

const data = [
    {
        x: 'abc',
        y: []
    },
    {
        x: '123',
        y: [1, 2, 3]
    }
]

console.log('begin')
fn(data).then(x => console.log('result:', x))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

关于javascript - Promise.all 位于带有 FP promise 的对象数组上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51568386/

相关文章:

javascript - jquery ui 可调整大小和可拖动元素已被覆盖

javascript - 为什么我的后端不更新数据库中的关键字数据列

node.js - Jasmine Node 测试子进程

java - 编写 Java 函数和使用者

python - 使用 python itertools 生成可迭代对象的可迭代对象。 (使用重复功能)

javascript - Connect-mongo 更新导致持续错误 : TypeError: Cannot read property 'Store' of undefined

javascript - 为什么 event.stopPropagation 也停止了我的 Bootstrap Collapse?

javascript - TypeScript 和运行时类型检查,2020 年的简单解决方案

javascript - promise 并确保 Node JS 准备就绪

haskell - 具有 kind * -> * 的类型的示例,该类型不能是 Functor 的实例