简体   繁体   English

Groovy - 等待承诺列表

[英]Groovy - Wait on list of promises

I have several promises in my program and I need to wait on all of them simulateneously before moving on. 我的程序中有几个承诺,我需要在继续之前模拟等待所有这些承诺。 For Grails , I found the following example: 对于Grails ,我发现了以下示例:

def p1 = task { 2 * 2 }
def p2 = task { 4 * 4 }
def p3 = task { 8 * 8 }
assert [4,16,64] == waitAll(p1, p2, p3)

I know Grails is heavily relying on GPars , but I cannot find the reference to waitAll anywhere in there. 我知道Grails在很大程度上依赖于GPars ,但我无法在那里的任何地方找到waitAll的引用。 Grails also supports PromiseList , which I cannot find in Groovy or GPars either. Grails还支持PromiseList ,我在GroovyGPars也找不到它。 Can anyone point me in the right direction? 谁能指出我正确的方向?

waitAll is a Grails specific static method from Promises class. waitAll是Promises类中的Grails特定静态方法。 It internally built on GPars whenAllBound method which you can use for your implementation. 它内部构建在GPars whenAllBound方法上,您可以将其用于实现。

Thanks to defectus and Feras Odeh , I could figure out the correct way of doing it with whenAllBound . 感谢defectusFeras Odeh ,我可以用whenAllBound找出正确的方法。 Just to save everyone else a bit of time, here is a working code example: 为了节省其他人一点时间,这是一个有效的代码示例:

import static groovyx.gpars.dataflow.Dataflow.task
import static groovyx.gpars.dataflow.Dataflow.whenAllBound;

def p1 = task { 2 * 2 }
def p2 = task { 4 * 4 }
def p3 = task { 8 * 8 }
def total = whenAllBound(p1, p2, p3, { List<?> values -> values })
assertTrue([4,16,64] == total.get())

whenAllBound expects a closure that is called with the results of all promises. whenAllBound期望使用所有promise 的结果调用闭包。 I simply collect them and return them as they are. 我只是收集它们并按原样返回它们。 Also, whenAllBound returns a promise itself, so you will need to call the .get() method on it (see assertion statement). 此外, whenAllBound本身返回一个promise ,因此您需要在其上调用.get()方法(请参阅assertion语句)。

The truth it's in the source code. 这是源代码中的真相。

import groovyx.gpars.dataflow.Dataflow

def <T> List<groovyx.gpars.dataflow.Promise<T>> toGparsPromises(List<Promise<T>> promises) {
    final List<groovyx.gpars.dataflow.Promise<T>> dataflowPromises = promises.collect() { it -> (groovyx.gpars.dataflow.Promise<T>)((GparsPromise<T>)it).internalPromise }
    dataflowPromises
}

private static Closure<List<?>> originalValuesClosure = { List<?> values -> values }

def <T> List<T> waitAll(List<Promise<T>> promises) {
    final groovyx.gpars.dataflow.Promise<List<T>> promise = (groovyx.gpars.dataflow.Promise<List<T>>)Dataflow.whenAllBound(toGparsPromises(promises), originalValuesClosure)
    return promise.get()
}

https://github.com/grails/grails-core/blob/master/grails-async/src/main/groovy/org/grails/async/factory/gpars/GparsPromiseFactory.groovy https://github.com/grails/grails-core/blob/master/grails-async/src/main/groovy/org/grails/async/factory/gpars/GparsPromiseFactory.groovy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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