[ 
https://issues.apache.org/jira/browse/GROOVY-9381?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18030740#comment-18030740
 ] 

Daniel Sun commented on GROOVY-9381:
------------------------------------

I polished the description of the ticket, any question and proposal will be 
welcomed.

> Support async/await like ES7
> ----------------------------
>
>                 Key: GROOVY-9381
>                 URL: https://issues.apache.org/jira/browse/GROOVY-9381
>             Project: Groovy
>          Issue Type: New Feature
>            Reporter: Daniel Sun
>            Priority: Major
>
> Here is the proposed syntax and backend API(Java's {{CompletableFuture}} or 
> GPars's {{Promise}}), but I think it's better for Groovy to have its own 
> {{Promise}} to decouple with Java API because async/await as a language 
> feature should be as stable as possible.
> {code:java}
> /**
>  * 1. An async function that simulates a network API call.
>  * The 'async' keyword implies it runs asynchronously without blocking.
>  */
> async fetchUserData(userId) {
>     println "Starting to fetch data for user ${userId}..."
>     
>     // Simulate a 1-second network delay.
>     Thread.sleep(1000) 
>     
>     println "Fetch successful!"
>     // The 'async' function implicitly returns a "CompletableFuture" or 
> "Promise" containing this value.
>     return [userId: userId, name: 'Daniel']
> }
> /**
>  * 2. An async function that uses 'await' to consume the result.
>  */
> async processUserData() {
>     println "Process started, preparing to fetch user data..."
>     
>     try {
>         // 'await' pauses this function until fetchUserData completes
>         // and returns the final result directly.
>         def user = await fetchUserData(1)
>         
>         println "Data received: ${user}"
>         return "Processing complete for ${user.name}."
>         
>     } catch (Exception e) {
>         return "An error occurred: ${e.message}"
>     }
> }
> // --- Execution ---
> println "Script starting..."
> // Kick off the entire asynchronous process.
> def future = processUserData()
> // This line executes immediately, proving the process is non-blocking.
> println "Script continues to run while user data is being fetched in the 
> background..."
> def result = future.get()
> println "Script finished: ${result}"
> {code}



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to