├── .eslintrc.cjs ├── .gitattributes ├── .github └── workflows │ ├── nodejs-test.yml │ └── release-please.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── renovate.json ├── rollup.config.js ├── src └── async-event-emitter.js ├── tests ├── async-event-emitter.test.js ├── pkg.test.cjs └── pkg.test.mjs └── tsconfig.json /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "env": { 3 | "es6": true, 4 | "node": true 5 | }, 6 | "extends": "eslint:recommended", 7 | "parserOptions": { 8 | "ecmaVersion": "latest", 9 | "sourceType": "module" 10 | }, 11 | "rules": { 12 | "indent": [ 13 | "error", 14 | 4 15 | ], 16 | "linebreak-style": [ 17 | "error", 18 | "unix" 19 | ], 20 | "quotes": [ 21 | "error", 22 | "double" 23 | ], 24 | "semi": [ 25 | "error", 26 | "always" 27 | ], 28 | "no-console": "error" 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | 3 | -------------------------------------------------------------------------------- /.github/workflows/nodejs-test.yml: -------------------------------------------------------------------------------- 1 | name: Node CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ${{ matrix.os }} 9 | 10 | strategy: 11 | matrix: 12 | os: [windows-latest, macOS-latest, ubuntu-latest] 13 | node: [14.x, 16.x, 18.x] 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Use Node.js ${{ matrix.node-version }} 18 | uses: actions/setup-node@v3 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | - name: npm install, build, and test 22 | run: | 23 | npm install 24 | npm run build --if-present 25 | npm test 26 | env: 27 | CI: true 28 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | name: release-please 6 | jobs: 7 | release-please: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: GoogleCloudPlatform/release-please-action@v2 11 | id: release 12 | with: 13 | release-type: node 14 | package-name: test-release-please 15 | # The logic below handles the npm publication: 16 | - uses: actions/checkout@v3 17 | # these if statements ensure that a publication only occurs when 18 | # a new release is created: 19 | if: ${{ steps.release.outputs.release_created }} 20 | - uses: actions/setup-node@v3 21 | with: 22 | node-version: 12 23 | registry-url: 'https://registry.npmjs.org' 24 | if: ${{ steps.release.outputs.release_created }} 25 | - run: npm ci 26 | if: ${{ steps.release.outputs.release_created }} 27 | - run: npm publish 28 | env: 29 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 30 | if: ${{ steps.release.outputs.release_created }} 31 | 32 | # Tweets out release announcement 33 | - run: 'npx @humanwhocodes/tweet "${{ github.event.repository.full_name }} v${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/v${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }}"' 34 | if: ${{ steps.release.outputs.release_created }} 35 | env: 36 | TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} 37 | TWITTER_CONSUMER_SECRET: ${{ secrets.TWITTER_CONSUMER_SECRET }} 38 | TWITTER_ACCESS_TOKEN_KEY: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }} 39 | TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # distribution files 64 | dist 65 | 66 | # test fixtures 67 | tests/fixtures/typescript-project/index.js 68 | 69 | # file used to generate env.d.ts 70 | dist/env.js 71 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ### [1.0.1](https://www.github.com/humanwhocodes/async-event-emitter/compare/v1.0.0...v1.0.1) (2022-08-10) 4 | 5 | 6 | ### Bug Fixes 7 | 8 | * Remove console.log ([f803a34](https://www.github.com/humanwhocodes/async-event-emitter/commit/f803a3412592b18c5aec8efc0e07a90ff402a44d)) 9 | 10 | ## 1.0.0 (2022-08-09) 11 | 12 | 13 | ### Features 14 | 15 | * Implement AsyncEventEmitter ([c153cd2](https://www.github.com/humanwhocodes/async-event-emitter/commit/c153cd2cc1f58bd4d9bdee9272fa3970144fd50b)) 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AsyncEventEmitter 2 | 3 | by [Nicholas C. Zakas](https://humanwhocodes.com) 4 | 5 | If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate). 6 | 7 | ## Description 8 | 9 | A utility for emitting events and responding with asynchronous functions. 10 | 11 | ## Usage 12 | 13 | ### Node.js 14 | 15 | Install using [npm][npm] or [yarn][yarn]: 16 | 17 | ``` 18 | npm install @humanwhocodes/async-event-emitter 19 | 20 | # or 21 | 22 | yarn add @humanwhocodes/async-event-emitter 23 | ``` 24 | 25 | Import into your Node.js project: 26 | 27 | ```js 28 | // CommonJS 29 | const { AsyncEventEmitter } = require("@humanwhocodes/async-event-emitter"); 30 | 31 | // ESM 32 | import { AsyncEventEmitter } from "@humanwhocodes/async-event-emitter"; 33 | ``` 34 | 35 | 36 | ### Deno 37 | 38 | Import into your Deno project: 39 | 40 | ```js 41 | import { AsyncEventEmitter } from "https://cdn.skypack.dev/@humanwhocodes/async-event-emitter?dts"; 42 | ``` 43 | 44 | ### Bun 45 | 46 | Install using this command: 47 | 48 | ``` 49 | bun add @humanwhocodes/async-event-emitter 50 | ``` 51 | 52 | Import into your Bun project: 53 | 54 | ```js 55 | import { AsyncEventEmitter } from "@humanwhocodes/async-event-emitter"; 56 | ``` 57 | 58 | ### Browser 59 | 60 | It's recommended to import the minified version to save bandwidth: 61 | 62 | ```js 63 | import { AsyncEventEmitter } from "https://cdn.skypack.dev/@humanwhocodes/async-event-emitter?min"; 64 | ``` 65 | 66 | However, you can also import the unminified version for debugging purposes: 67 | 68 | ```js 69 | import { AsyncEventEmitter } from "https://cdn.skypack.dev/@humanwhocodes/async-event-emitter"; 70 | ``` 71 | 72 | ## API 73 | 74 | After importing, create a new instance of `AsyncEventEmitter` to start emitting events: 75 | 76 | ```js 77 | const emitter = new AsyncEventEmitter(); 78 | 79 | // add some event handlers - functions can be async or not 80 | emitter.on("foo", async () => "hello!"); 81 | emitter.on("foo", () => "goodbye!"); 82 | 83 | // emit an event 84 | const results = await emitter.emit("foo"); 85 | console.log(results); // ["hello!", "goodbye!"] 86 | 87 | // you can also pass arguments 88 | emitter.on("exclaim", suffix => "hello" + suffix); 89 | emitter.on("exclaim", suffix => "goodbye" + suffix); 90 | 91 | const results = await emitter.emit("exclaim", "!"); 92 | console.log(results); // ["hello!", "goodbye!"] 93 | 94 | // get the number of handlers for an event 95 | const count = emitter.listenerCount("exclaim"); 96 | console.log(count); // 2 97 | 98 | // remove any unwanted handlers 99 | const handler = () => {}; 100 | emitter.on("bar", handler); 101 | emitter.off("bar", handler); 102 | 103 | const results = await emitter.emit("bar"); 104 | console.log(results); // [] 105 | 106 | ``` 107 | 108 | ## Developer Setup 109 | 110 | 1. Fork the repository 111 | 2. Clone your fork 112 | 3. Run `npm install` to setup dependencies 113 | 4. Run `npm test` to run tests 114 | 115 | ## License 116 | 117 | Apache 2.0 118 | 119 | [npm]: https://npmjs.com/ 120 | [yarn]: https://yarnpkg.com/ 121 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@humanwhocodes/async-event-emitter", 3 | "version": "1.0.1", 4 | "description": "Async event emitter", 5 | "main": "dist/async-event-emitter.cjs", 6 | "module": "dist/async-event-emitter.js", 7 | "type": "module", 8 | "types": "dist/async-event-emitter.d.ts", 9 | "exports": { 10 | "require": "./dist/async-event-emitter.cjs", 11 | "import": "./dist/async-event-emitter.js" 12 | }, 13 | "files": [ 14 | "dist" 15 | ], 16 | "publishConfig": { 17 | "access": "public" 18 | }, 19 | "gitHooks": { 20 | "pre-commit": "lint-staged" 21 | }, 22 | "lint-staged": { 23 | "*.js": [ 24 | "eslint --fix" 25 | ] 26 | }, 27 | "funding": { 28 | "type": "github", 29 | "url": "https://github.com/sponsors/nzakas" 30 | }, 31 | "scripts": { 32 | "build": "rollup -c && tsc", 33 | "prepare": "npm run build", 34 | "lint": "eslint src/ tests/", 35 | "pretest": "npm run build", 36 | "test:unit": "c8 mocha tests/async-event-emitter.test.js", 37 | "test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs", 38 | "test": "npm run test:unit && npm run test:build" 39 | }, 40 | "repository": { 41 | "type": "git", 42 | "url": "git+https://github.com/humanwhocodes/async-event-emitter.git" 43 | }, 44 | "keywords": [ 45 | "events", 46 | "eventemitter", 47 | "async", 48 | "promises" 49 | ], 50 | "engines": { 51 | "node": ">=14" 52 | }, 53 | "author": "Nicholas C. Zaks", 54 | "license": "Apache-2.0", 55 | "devDependencies": { 56 | "c8": "7.12.0", 57 | "chai": "4.3.6", 58 | "eslint": "8.21.0", 59 | "lint-staged": "13.0.3", 60 | "mocha": "9.2.2", 61 | "rollup": "2.77.2", 62 | "typescript": "4.7.4", 63 | "yorkie": "2.0.0" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Rollup config file 3 | */ 4 | 5 | export default [ 6 | { 7 | input: "src/async-event-emitter.js", 8 | output: [ 9 | { 10 | file: "dist/async-event-emitter.cjs", 11 | format: "cjs" 12 | }, 13 | { 14 | file: "dist/async-event-emitter.js", 15 | format: "esm" 16 | } 17 | ] 18 | } 19 | ]; 20 | -------------------------------------------------------------------------------- /src/async-event-emitter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview A utility async events. 3 | */ 4 | 5 | //----------------------------------------------------------------------------- 6 | // Types 7 | //----------------------------------------------------------------------------- 8 | 9 | /** @typedef {(...args:any)=>Promise} EventHandler */ 10 | 11 | //----------------------------------------------------------------------------- 12 | // Helpers 13 | //----------------------------------------------------------------------------- 14 | 15 | /** 16 | * Asserts that a given value is a string. 17 | * @param {any} value The value to test. 18 | * @returns {void} 19 | * @throws {TypeError} If the value is not a string. 20 | */ 21 | function assertNonEmptyString(value) { 22 | if (!value || typeof value !== "string") { 23 | throw new TypeError(`Expected a non-empty string but found ${ String(value) }.`); 24 | } 25 | } 26 | 27 | /** 28 | * Asserts that a given value is a function. 29 | * @param {any} value The value to test. 30 | * @returns {void} 31 | * @throws {TypeError} If the value is not a function. 32 | */ 33 | function assertFunction(value) { 34 | if (!value || typeof value !== "function") { 35 | throw new TypeError(`Expected a function but found ${ String(value) }.`); 36 | } 37 | } 38 | 39 | //----------------------------------------------------------------------------- 40 | // Exports 41 | //----------------------------------------------------------------------------- 42 | 43 | /** 44 | * Object for publishing and subscribing to event with asynchronous 45 | * event handlers. 46 | */ 47 | export class AsyncEventEmitter { 48 | 49 | /** 50 | * Tracks event handlers for all events. 51 | * @type {Map>} 52 | */ 53 | #handlers = new Map(); 54 | 55 | /** 56 | * Emits a given event and passes the given arguments to each 57 | * event handler. 58 | * @param {string} eventName The name of the event to emit. 59 | * @param {...any?} args Any additional arguments to pass to the 60 | * event handlers. 61 | * @returns {Array|any} An array of resolved values if all 62 | * event handlers pass or a single rejected value if any of 63 | * the event handlers fail. 64 | */ 65 | emit(eventName, ...args) { 66 | 67 | assertNonEmptyString(eventName); 68 | 69 | const handlers = this.#handlers.get(eventName) || []; 70 | 71 | return Promise.all( 72 | handlers.map(handler => { 73 | return handler(...args); 74 | }) 75 | ); 76 | } 77 | 78 | /** 79 | * Retrieves the number of listeners for the given event. 80 | * @param {string} eventName The name of the event. 81 | * @returns {number} The number of event handlers for this event. 82 | */ 83 | listenerCount(eventName) { 84 | 85 | assertNonEmptyString(eventName); 86 | 87 | let handlers = this.#handlers.get(eventName); 88 | 89 | if (!handlers) { 90 | return 0; 91 | } 92 | return handlers.length; 93 | } 94 | 95 | /** 96 | * Removes an event handler for the given event name. 97 | * @param {string} eventName The name of the event. 98 | * @param {EventHandler} handler The function to remove. 99 | * @returns {void} 100 | */ 101 | off(eventName, handler) { 102 | 103 | assertNonEmptyString(eventName); 104 | assertFunction(handler); 105 | 106 | let handlers = this.#handlers.get(eventName); 107 | 108 | if (handlers) { 109 | 110 | const handlerIndex = handlers.indexOf(handler); 111 | 112 | if (handlerIndex > -1) { 113 | handlers.splice(handlerIndex, 1); 114 | } 115 | } 116 | 117 | } 118 | 119 | /** 120 | * Assigns an event handler for the given event name. 121 | * @param {string} eventName The name of the event. 122 | * @param {EventHandler} handler The function to call when the 123 | * event occurs. 124 | * @returns {void} 125 | */ 126 | on(eventName, handler) { 127 | 128 | assertNonEmptyString(eventName); 129 | assertFunction(handler); 130 | 131 | let handlers = this.#handlers.get(eventName); 132 | 133 | if (!handlers) { 134 | /** @type {Array} */ 135 | handlers = []; 136 | this.#handlers.set(eventName, handlers); 137 | } 138 | 139 | handlers.push(handler); 140 | } 141 | 142 | } 143 | -------------------------------------------------------------------------------- /tests/async-event-emitter.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Tests for the AsyncEventEmitter class. 3 | */ 4 | /*global describe, it*/ 5 | 6 | //----------------------------------------------------------------------------- 7 | // Requirements 8 | //----------------------------------------------------------------------------- 9 | 10 | import { AsyncEventEmitter } from "../src/async-event-emitter.js"; 11 | import { expect } from "chai"; 12 | 13 | //----------------------------------------------------------------------------- 14 | // Tests 15 | //----------------------------------------------------------------------------- 16 | 17 | describe("AsyncEventEmitter", () => { 18 | 19 | describe("on()", () => { 20 | it("should throw an error if the event name is empty", () => { 21 | const emitter = new AsyncEventEmitter(); 22 | 23 | expect(() => { 24 | emitter.on("", () => {}); 25 | }).to.throw(/Expected a non-empty string/); 26 | 27 | }); 28 | 29 | it("should throw an error if the event name is not a string", () => { 30 | const emitter = new AsyncEventEmitter(); 31 | 32 | expect(() => { 33 | emitter.on(5, () => {}); 34 | }).to.throw(/Expected a non-empty string/); 35 | 36 | }); 37 | 38 | it("should throw an error if the event handler is not a function", () => { 39 | const emitter = new AsyncEventEmitter(); 40 | 41 | expect(() => { 42 | emitter.on("foo", 5); 43 | }).to.throw(/Expected a function/); 44 | 45 | }); 46 | }); 47 | 48 | describe("emit()", () => { 49 | it("should throw an error if the event name is empty", () => { 50 | const emitter = new AsyncEventEmitter(); 51 | 52 | expect(() => { 53 | emitter.emit(""); 54 | }).to.throw(/Expected a non-empty string/); 55 | 56 | }); 57 | 58 | it("should throw an error if the event name is not a string", () => { 59 | const emitter = new AsyncEventEmitter(); 60 | 61 | expect(() => { 62 | emitter.emit(true); 63 | }).to.throw(/Expected a non-empty string/); 64 | 65 | }); 66 | }); 67 | 68 | describe("on/emit()", () => { 69 | 70 | it("should return an empty array when no event handlers exist", async () => { 71 | const emitter = new AsyncEventEmitter(); 72 | const result = await emitter.emit("foo"); 73 | expect(result).to.deep.equal([]); 74 | }); 75 | 76 | it("should call an async event handler when event is emitted", async () => { 77 | const emitter = new AsyncEventEmitter(); 78 | 79 | emitter.on("foo", async () => "bar"); 80 | 81 | const result = await emitter.emit("foo"); 82 | expect(result).to.deep.equal(["bar"]); 83 | }); 84 | 85 | it("should call multiple async event handlers when event is emitted", async () => { 86 | const emitter = new AsyncEventEmitter(); 87 | 88 | emitter.on("foo", async () => "bar"); 89 | emitter.on("foo", async () => "baz"); 90 | 91 | const result = await emitter.emit("foo"); 92 | expect(result).to.deep.equal(["bar", "baz"]); 93 | }); 94 | 95 | it("should call multiple async event handlers with arguments when event is emitted", async () => { 96 | const emitter = new AsyncEventEmitter(); 97 | 98 | emitter.on("foo", async suffix => "bar" + suffix); 99 | emitter.on("foo", async suffix => "baz" + suffix); 100 | 101 | const result = await emitter.emit("foo", "x"); 102 | expect(result).to.deep.equal(["barx", "bazx"]); 103 | }); 104 | 105 | 106 | it("should call multiple sync event handlers with arguments when event is emitted", async () => { 107 | const emitter = new AsyncEventEmitter(); 108 | 109 | emitter.on("foo", suffix => "bar" + suffix); 110 | emitter.on("foo", suffix => "baz" + suffix); 111 | 112 | const result = await emitter.emit("foo", "x"); 113 | expect(result).to.deep.equal(["barx", "bazx"]); 114 | }); 115 | 116 | it("should call multiple event handlers with arguments when multiple events are emitted", async () => { 117 | const emitter = new AsyncEventEmitter(); 118 | 119 | emitter.on("foo1", suffix => "bar" + suffix); 120 | emitter.on("foo2", suffix => "baz" + suffix); 121 | 122 | const result1 = await emitter.emit("foo1", "x"); 123 | const result2 = await emitter.emit("foo2", "x"); 124 | 125 | expect(result1).to.deep.equal(["barx"]); 126 | expect(result2).to.deep.equal(["bazx"]); 127 | }); 128 | 129 | 130 | }); 131 | 132 | describe("off()", () => { 133 | 134 | it("should remove event handler and not call it when event is emitted", async () => { 135 | const emitter = new AsyncEventEmitter(); 136 | 137 | const handler = async suffix => "bar" + suffix; 138 | 139 | emitter.on("foo", handler); 140 | emitter.off("foo", handler); 141 | 142 | const result = await emitter.emit("foo", "x"); 143 | expect(result).to.deep.equal([]); 144 | }); 145 | 146 | it("should throw an error if the event name is empty", () => { 147 | const emitter = new AsyncEventEmitter(); 148 | 149 | expect(() => { 150 | emitter.off("", () => { }); 151 | }).to.throw(/Expected a non-empty string/); 152 | 153 | }); 154 | 155 | it("should throw an error if the event name is not a string", () => { 156 | const emitter = new AsyncEventEmitter(); 157 | 158 | expect(() => { 159 | emitter.off(5, () => { }); 160 | }).to.throw(/Expected a non-empty string/); 161 | 162 | }); 163 | 164 | it("should throw an error if the event handler is not a function", () => { 165 | const emitter = new AsyncEventEmitter(); 166 | 167 | expect(() => { 168 | emitter.off("foo", 5); 169 | }).to.throw(/Expected a function/); 170 | 171 | }); 172 | 173 | 174 | }); 175 | 176 | describe("listenerCount()", () => { 177 | 178 | it("should return 0 when there are no event handlers", () => { 179 | const emitter = new AsyncEventEmitter(); 180 | const result = emitter.listenerCount("foo"); 181 | expect(result).to.equal(0); 182 | }); 183 | 184 | it("should return 1 when there is one event handler", () => { 185 | const emitter = new AsyncEventEmitter(); 186 | 187 | emitter.on("foo", async () => "bar"); 188 | 189 | const result = emitter.listenerCount("foo"); 190 | expect(result).to.equal(1); 191 | }); 192 | 193 | it("should call multiple async event handlers when event is emitted", () => { 194 | const emitter = new AsyncEventEmitter(); 195 | 196 | emitter.on("foo", async () => "bar"); 197 | emitter.on("foo", async () => "baz"); 198 | 199 | const result = emitter.listenerCount("foo"); 200 | expect(result).to.equal(2); 201 | }); 202 | 203 | it("should throw an error if the event name is empty", () => { 204 | const emitter = new AsyncEventEmitter(); 205 | 206 | expect(() => { 207 | emitter.listenerCount("", () => { }); 208 | }).to.throw(/Expected a non-empty string/); 209 | 210 | }); 211 | 212 | it("should throw an error if the event name is not a string", () => { 213 | const emitter = new AsyncEventEmitter(); 214 | 215 | expect(() => { 216 | emitter.listenerCount(5, () => { }); 217 | }).to.throw(/Expected a non-empty string/); 218 | 219 | }); 220 | 221 | 222 | }); 223 | 224 | }); 225 | -------------------------------------------------------------------------------- /tests/pkg.test.cjs: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Tests that Common JS can access npm package. 3 | */ 4 | 5 | const { AsyncEventEmitter } = require("../"); 6 | new AsyncEventEmitter(); 7 | console.log("CommonJS load: success"); 8 | -------------------------------------------------------------------------------- /tests/pkg.test.mjs: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Tests that ESM can access npm package. 3 | */ 4 | 5 | import fs from "fs"; 6 | 7 | const pkg = JSON.parse(fs.readFileSync("./package.json", "utf8")); 8 | const url = new URL("../" + pkg.exports.import, import.meta.url); 9 | 10 | import(url).then(({ AsyncEventEmitter }) => { 11 | new AsyncEventEmitter(); 12 | console.log("ESM load: success"); 13 | }); 14 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "src/async-event-emitter.js" 4 | ], 5 | "compilerOptions": { 6 | "declaration": true, 7 | "emitDeclarationOnly": true, 8 | "allowJs": true, 9 | "checkJs": true, 10 | "target": "ES2015", 11 | "outDir": "dist" 12 | } 13 | } 14 | --------------------------------------------------------------------------------