{"id":22443136,"url":"https://github.com/riversun/java-promise","last_synced_at":"2025-08-01T18:34:01.564Z","repository":{"id":57740065,"uuid":"184093415","full_name":"riversun/java-promise","owner":"riversun","description":"Promise library for java.You can do the same thing with JavaScript's Promise in java! Concurrent library.","archived":false,"fork":false,"pushed_at":"2019-05-03T17:55:51.000Z","size":83,"stargazers_count":15,"open_issues_count":2,"forks_count":6,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-24T12:42:45.439Z","etag":null,"topics":["asynchronous","concurrency-library","java","javascript","multithreading","promise"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/riversun.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-04-29T15:08:34.000Z","updated_at":"2023-10-13T14:08:22.000Z","dependencies_parsed_at":"2022-08-30T10:51:29.027Z","dependency_job_id":null,"html_url":"https://github.com/riversun/java-promise","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fjava-promise","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fjava-promise/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fjava-promise/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fjava-promise/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/riversun","download_url":"https://codeload.github.com/riversun/java-promise/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228398855,"owners_count":17913682,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asynchronous","concurrency-library","java","javascript","multithreading","promise"],"created_at":"2024-12-06T02:22:43.399Z","updated_at":"2024-12-06T02:22:44.045Z","avatar_url":"https://github.com/riversun.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Overview\n**java-promise** is a Promise Library for Java.\n\n- You can easily control asynchronous operations like JavaScript's **[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)**.\n- Supports both synchronous and asynchronous execution.\n\nIt is licensed under [MIT](https://opensource.org/licenses/MIT).\n\n[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.riversun/java-promise/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.riversun/java-promise)\n\n\n# Quick Look\n\n**Writing a Promise in Javascript**\n\nA typical example of using promise in JavaScript is:\n\n```JavaScript\nPromise.resolve('foo')\n    .then(function (data) {\n        return new Promise(function (resolve, reject) {\n            setTimeout(function () {\n                const newData = data + 'bar';\n                resolve(newData);\n            }, 1);\n        });\n    })\n    .then(function (data) {\n        return new Promise(function (resolve, reject) {\n            console.log(data);\n        });\n    });\nconsole.log(\"Promise in JavaScript\");\n```\n\nResult:\n\n```\nPromise in JavaScript\nfoobar\n```\n\n**Writing a Promise in java-promise**\n\nWrite the same thing using **java-promise**\n\n```Java\nimport org.riversun.promise.Promise;\npublic class Example {\n\n    public static void main(String[] args) {\n        Promise.resolve(\"foo\")\n                .then(new Promise((action, data) -\u003e {\n                    new Thread(() -\u003e {\n                        String newData = data + \"bar\";\n                        action.resolve(newData);\n                    }).start();\n                }))\n                .then(new Promise((action, data) -\u003e {\n                    System.out.println(data);\n                    action.resolve();\n                }))\n                .start();\n        System.out.println(\"Promise in Java\");\n    }\n}\n```\n\nResult:\n\n```\nPromise in Java\nfoobar\n```\n\n**Syntax:**  \nYes,you can write in a syntax similar to JavaScript as follows:\n\n```Java\nPromise.resolve()\n        .then(new Promise(funcFulfilled1), new Promise(funcRejected1))\n        .then(new Promise(functionFulfilled2), new Promise(functionRejected2))\n        .start();\n```        \n\n\u003cimg src=\"https://user-images.githubusercontent.com/11747460/56907143-a11fa380-6ade-11e9-9d23-195cce2c1543.png\"\u003e\n\n# Dependency\n\n**Maven**\n\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003eorg.riversun\u003c/groupId\u003e\n    \u003cartifactId\u003ejava-promise\u003c/artifactId\u003e\n    \u003cversion\u003e1.1.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n**Gradle**\n\n```\ncompile group: 'org.riversun', name: 'java-promise', version: '1.1.0'\n```\n\n# Quick Start\n\n### Execute sequentially by chained \"then\"\n\n- Use **Promise.then()** to chain operations.  \n- Write your logic in **Func.run(action,data)**.\n- Start operation by **Promise.start** and run **asynchronously**(run on worker thread)\n- Calling **action.resolve** makes the promise **fullfilled** state and passes the **result** to the next then\n\n```java\npublic class Example00 {\n\n    public static void main(String[] args) {\n\n        Func function1 = (action, data) -\u003e {\n            new Thread(() -\u003e {\n                System.out.println(\"Process-1\");\n                try {\n                    Thread.sleep(500);\n                } catch (InterruptedException e) {}\n                //Specify result value.(Any type can be specified)\n                action.resolve(\"Result-1\");\n            }).start();\n        };\n\n        Func function2 = (action, data) -\u003e {\n            System.out.println(\"Process-2 result=\" + data);\n            action.resolve();\n        };\n\n        Promise.resolve()\n                .then(new Promise(function1))\n                .then(new Promise(function2))\n                .start();// start Promise operation\n\n        System.out.println(\"Hello,Promise\");\n    }\n}\n```\n\n**Diagram:**\n\u003cimg src=\"https://user-images.githubusercontent.com/11747460/56915517-acc89580-6af1-11e9-9ab2-c4274e8675ed.png\"\u003e\n\n**Result:**\n\n```\nHello,Promise\nProcess-1\nProcess-1 result=Result-1\n```\n\n**Tips**\n\nIt's also OK to just write ``Promise.then(func) ``.\n\n```Java\nPromise.resolve()\n        .then(function1)\n        .then(function2)\n        .start();// start Promise operation\n```        \n\n# Description\n### What is \"**Func**\" ?\n\n**Func** is a java interface equivalent to JavaScript's **Function** for argument of **#then**\n\n```java\npublic interface Func {\n\tpublic void run(Action action, Object data) throws Exception;\n}\n```\n\nYou can write **Func** like a JavaScript function.  \nI want to show two ways of implementing **Func** class.\n\nNo.1)Write **Func** object in the normal way.\n\n```Java\nFunc function = new Func() {\n    @Override\n    public void run(Action action, Object data) throws Exception {\n        System.out.println(\"Process\");//write your logic\n        action.resolve();\n    }\n};\n```\n\nNo.2)Write **Func** object using lambda expression.\n\n```Java\nFunc function = (action, data) -\u003e {\n    System.out.println(\"Process\");//write your logic\n    action.resolve();\n};\n```\n\n### What is \"**Action**\" ?\n\nAction object is an argument of **Func#run** method.  \n\n- Call **action.resolve( [fulfillment value] )** to make the Promise's status **fulfilled** and move on to the next processing(specified by then) with the result(**fulfillment value**).\n\n```Java\naction.resolve(\"Success\");\n```\n\n- Call **action.reject( [rejection reason] )** to make the Promise's status **rejected** and move on to the next processing(specified by then) with the result(**rejection reason**).\n\n```Java\naction.reject(\"Failure\");\n```\n\n- Argument is optional, you can call **action.resolve()** or **action.reject()**\n\n```Java\naction.resolve();//Argument can be omitted\n```\n\n# Usage\n\n### Rejection\n\nIf **action.reject()** is called, or if an **exception thrown** while executing **Func.run()**, **rejected** status is set to Promise, and the **onRejected** function specified to **then** is called.\n\n- call ``action.reject``\n\n```Java\nFunc function = (action, data) -\u003e {\n  action.reject(\"Failure\");\n};\n```\n\n- throw an exception\n\n```Java\nFunc function = (action, data) -\u003e {\n  throw new Exception(\"something\");\n};\n\n```\n\nLet's see **Promise.then()** method,  \nthe **2nd argument** of **Promise.then()** can be set to a **Func** to receive the result of **rejection** when receiving the result of **then**.\n\n- **Syntax**  \nUsage ``Promise.then(onFulfilled[, onRejected]);``\n\n- **onFulfilled** is a **Func** object called if the Promise is fulfilled.  \nYou can receive the previous execution **\"fulfilled\"** result as an argument named **data**.\n\n- **onRejected** is a **Func** object called if the Promise is rejected.  \nYou can receive the previous execution **\"rejected\"** result(mainly the objects are exceptions) as an argument named **data**.\n\n```Java\n//Rejection\npublic class ExampleRejection {\n    public static void main(String[] args) {\n        Promise.resolve()\n                .then((action, data) -\u003e {\n                    System.out.println(\"Process-1\");\n                    action.reject();\n                })\n                .then(\n                        // call when resolved\n                        (action, data) -\u003e {\n                            System.out.println(\"Resolved Process-2\");\n                            action.resolve();\n                        },\n                        // call when rejected\n                        (action, data) -\u003e {\n                            System.out.println(\"Rejected Process-2\");\n                            action.resolve();\n                        })\n                .start();// start Promise operation\n\n        System.out.println(\"Hello,Promise\");\n    }\n}\n```\n\n**Diagram:**\n\n\u003cimg src=\"https://user-images.githubusercontent.com/11747460/56916023-efd73880-6af2-11e9-8f92-fae5eff48e32.png\"\u003e\n\n**Result:**\n\n```\nHello,Promise\nProcess-1\nRejected Process-2\n```\n\n\n### Promise.always\n\n**Promise.always()** always receive both **fulfilled** and **rejected** results.\n\n```Java\npublic class ExampleAlways {\n\n    public static void main(String[] args) {\n        Func func2OutReject = (action, data) -\u003e {\n            action.reject(\"I send REJECT\");\n            //action.resolve(\"I send RESOLVE\");\n        };\n        Func func2ReceiveAlways = (action, data) -\u003e {\n            System.out.println(\"Received:\" + data);\n            action.resolve();\n        };\n        Promise.resolve()\n                .then(func2OutReject)\n                .always(func2ReceiveAlways)\n                .start();\n    }\n}\n```\n\n**Diagram:**\n\u003cimg src=\"https://user-images.githubusercontent.com/11747460/56918747-d1c10680-6af9-11e9-886b-2e7949d1114c.png\"\u003e\n\n**Result**\n\n```\nReceived:I send REJECT\n```\n\n### Promise.all\n\nExecute multiple promises at the same time, and after all executions are complete, move to the next processing with then\n\n- Execute multiple promises simultaneously and wait until all the execution is finished before proceeding.\n- If all finishes with resolve, execution results will be stored as **java.util.List\u003cObject\\\u003e** in the order of invocation.\n- If there is even one rejection, store that rejection reason in the result when the rejection occurs and move on to the next \"then\".\n\n```Java\npublic class ExampleAll {\n    public static void main(String[] args) {\n        Func func1 = (action, data) -\u003e {\n            Promise.sleep(1000);\n            System.out.println(\"func1 running\");\n            action.resolve(\"func1-result\");\n        };\n        Func func2 = (action, data) -\u003e {\n            Promise.sleep(500);\n            System.out.println(\"func2 running\");\n            action.resolve(\"func2-result\");\n        };\n        Func func3 = (action, data) -\u003e {\n            Promise.sleep(1500);\n            System.out.println(\"func3 running\");\n            action.resolve(\"func3-result\");\n        };\n        Func funcGetResult = (action, data) -\u003e {\n            List\u003cObject\u003e resultList = (List\u003cObject\u003e) data;\n            for (int i = 0; i \u003c resultList.size(); i++) {\n                Object o = resultList.get(i);\n                System.out.println(\"No.\" + (i + 1) + \" result is \" + o);\n            }\n            action.resolve();\n        };\n        Promise.all(func1, func2, func3)\n                .always(funcGetResult)\n                .start();\n    }\n}\n```\n\n**Diagram:**\n\u003cimg src=\"https://user-images.githubusercontent.com/11747460/57029142-d6adc380-6c7b-11e9-9e15-ddb84dad0d24.png\"\u003e\n\n\n**Result:**\n\n```\nfunc2 running\nfunc1 running\nfunc3 running\nNo.1 result is func1-result\nNo.2 result is func2-result\nNo.3 result is func3-result\n```\n\n### Threading\n\nIt is also possible to execute Promise processing on the specified executor.\n\u003cfont color=red\u003eNote if you use your own executor, remember to shut it down after use.\nIf you use your own executor, it will **NOT** be shutdown automatically\u003c/font\u003e　　\n\nAt least one worker thread to be used in Promise.all,\nand one thread for overall asynchronous execution, so a total of \u003cfont color=red\u003etwo or more threads\u003c/font\u003e must be needed.\n\n```Java\npublic class Example {\n\n    public static void main(String[] args) {\n\n        final ExecutorService myExecutor = Executors.newFixedThreadPool(5);\n\n        Func func1 = (action, data) -\u003e {\n            System.out.println(\"func1 on \" + Thread.currentThread().getName());\n            action.resolve();\n        };\n\n        Func func2 = (action, data) -\u003e {\n            System.out.println(\"func2 on \" + Thread.currentThread().getName());\n            action.resolve();\n        };\n\n        Func func3 = (action, data) -\u003e {\n            System.out.println(\"func3 on \" + Thread.currentThread().getName());\n            action.resolve();\n        };\n\n        Promise.all(myExecutor, func1, func2, func3)\n                .then((action, data) -\u003e {\n                    System.out.println(\"final process on \" + Thread.currentThread().getName());\n                    myExecutor.shutdown();//If you use your own executor, remember to shut it down after use\n                    action.resolve();\n                })\n                .start();\n    }\n}\n```\n\n**Result:**\n\n```\nfunc1 on pool-1-thread-2\nfunc2 on pool-1-thread-3\nfunc3 on pool-1-thread-4\nfinal process on pool-1-thread-1\n```\n\n# SyncPromise\n\nSyncPromise, as the name implies, is a synchronous promise.  \nWhile Promise is executed asynchronously, SyncPromise does NOT move next while it is chained by \"then\".  \nAll other features are the same as Promise.\n\n```Java\npublic class Example02 {\n\n    public static void main(String[] args) {\n        Func func1 = (action, data) -\u003e {\n            new Thread(() -\u003e {\n                System.out.println(\"Process-1\");\n                action.resolve();\n            }).start();\n\n        };\n        Func func2 = (action, data) -\u003e {\n            new Thread(() -\u003e {\n                System.out.println(\"Process-2\");\n                action.resolve();\n            }).start();\n\n        };\n        SyncPromise.resolve()\n                .then(func1)\n                .then(func2)\n                .start();\n        System.out.println(\"Hello,Promise\");\n    }\n}\n```\n\n**Result:**\n\n```\nProcess-1\nProcess-2\nHello,Promise\n```\n\nEven if **func1** and **func2** are executed in a thread,  \n``System.out.println(\"Hello,Promise\")`` is always executed after that.Because **SyncPromise** is synchronous execution.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Friversun%2Fjava-promise","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Friversun%2Fjava-promise","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Friversun%2Fjava-promise/lists"}