简体   繁体   English

在承诺中使用Ramda拒绝

[英]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函数无关。

Update 更新

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调用返回truePromise.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM