I want to write an asynchronous function that accepts a closure with handlers like HTTPBuilder.request does. How is the function written?
When I call the function, it will look like this:
// 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'
}
}
The “body” of
myFunctionis actually a third parameter of typeClosure. When you declare it, it will actually have three parameters:arg1,arg2, and one more containing the body.In
myFunctioncall the body closure with a delegate. The delegate holds thestatus.successandstatus.failureevent handler closures. Then do your async operation and capture the result. Finally, invoke the appropriate result handler closure. The skeleton for a function like this would look something like this: