所以,我正在使用 NodeJS 和 Ramda,并且我有一个对象数组,例如:
[
{
x: 'abc',
y: []
},
{
x: '123',
y: [1, 2, 3]
}
]
然后我想在返回 promise 的请求中使用 x
,结果是这样的(使用 Ramda 的 over
和 lensProp
):
[
{
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/