[英]Using Ramda reject with Promises
How can Ramda.reject() be used with Promises? Ramda.reject()如何与Promises一起使用?
map()
can work like this map()
可以像这样工作
const data = [ {id: 1}, {id: 2} ]
const userIsAdmin = (user) => isAdmin(user) // async database call
const result = await Promise.all(R.map(userIsAdmin, data))
console.log(result) // [true, false]
But what I really want is to get the user ids back, but with admins rejected. 但是我真正想要的是找回用户ID,但拒绝管理员。 I've tried the following code and other variations using
pipeP
. 我已经使用
pipeP
尝试了以下代码和其他变体。
await Promise.all(R.reject(async (d) => await userIsAdmin(d))(data))
How can this be done? 如何才能做到这一点?
An alternative is to refactor isAdmin()
to accept an array and just wait for one promise to complete. 另一种方法是重构
isAdmin()
以接受一个数组,然后等待一个承诺完成。
I'm not sure I follow entirely, but can you not simply use reject
on the results of Promise.all
? 我不确定我是否会完全遵循,但是您能否不能
Promise.all
的结果使用reject
?
const result = await Promise.all(R.map(asyncFn, data))
console.log(result) //=> [true, false]
console.log(R.filter(R.identity, result)) //=> [true]
But perhaps there's some confusion. 但是,也许有些混乱。 You do want to use
reject
for what it's meant to do, right? 您确实想将
reject
用于其意图,对吗? It is simply a variant of filter
with the predicate reversed, ie the (curried) equivalent of (fn, list) => R.filter(R.complement(fn), list)
. 它只是谓词颠倒的
filter
一种变体,即(fn, list) => R.filter(R.complement(fn), list)
的(咖喱)等价物。 It has nothing to do with the reject
function supplied to the callback given in the Promise constructor. 它与提供给Promise构造函数中的回调函数的
reject
函数无关。
With the updated question, I think the easiest approach is still to use reject
on the results of the Promise.all
call, but you will probably have to combine it with the original data. 对于更新的问题,我认为最简单的方法仍然是对
Promise.all
调用的结果使用reject
,但您可能必须将其与原始数据结合起来。 Something like: 就像是:
const removeAdmins = pipe(zip, reject(head), pluck(1))
removeAdmins(result, data)
zip
combines the two (equal-length) lists into pairs. zip
将两个(等长)列表组合成对。 Then calling head
on the pair gives you back the boolean, so reject(head)
filters out those that returned true
from your Promise.all
calls. 然后在该对上调用
head
可以返回布尔值,因此reject(head)
过滤掉那些从Promise.all
调用返回true
的Promise.all
。 Then pluck(1)
returns the second element (the original object) from each remaining pair. 然后
pluck(1)
)从其余每个对中返回第二个元素(原始对象)。
Would that do what you want? 那会做你想要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.