我想编写一个异步函数,它接受一个像HTTPBuilder.request这样的处理程序的闭包。函数是如何写的?
当我调用该函数时,它将如下所示:
// calling my function now - we'll process the results when status is available...
myFunction(arg1, arg2) {
status.success = { result ->
println 'cool'
}
status.failure = { result ->
println 'not cool'
}
}
答案 0 :(得分:1)
myFunction
的“正文”实际上是Closure
类型的第三个参数。声明它时,它实际上会有三个参数:arg1
,arg2
,还有一个参数包含正文。
在myFunction
中使用委托调用正文闭包。委托持有status.success
和status.failure
事件处理程序闭包。然后执行异步操作并捕获结果。最后,调用适当的结果处理程序闭包。像这样的函数的骨架看起来像这样:
def myFunction(arg1, arg2, Closure body) {
def delegateMap = [status:[:]]
body.delegate = delegateMap
body.call()
// start async process
Thread.start {
def result = doAsyncStuff()
if (isSuccess(result) && delegateMap.status.success) {
delegateMap.status.success.call(result)
}
else if (isFailure(result) && delegateMap.status.failure) {
delegateMap.status.failure.call(result)
}
}
}