Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: remove async library #2514

Merged
merged 2 commits into from
Jan 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/util/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@
"dependencies": {
"@chainsafe/ssz": "^0.10.0",
"@ethereumjs/rlp": "^4.0.0",
"async": "^3.2.4",
"ethereum-cryptography": "^1.1.2"
},
"devDependencies": {
Expand Down
55 changes: 32 additions & 23 deletions packages/util/src/asyncEventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
* https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/async-eventemitter
*/

import { eachSeries } from 'async'
import { EventEmitter } from 'events'
type AsyncListener<T, R> =
| ((data: T, callback?: (result?: R) => void) => Promise<R>)
Expand All @@ -16,6 +15,37 @@ export interface EventMap {
[event: string]: AsyncListener<any, any>
}

async function runInSeries(
context: any,
tasks: Array<(data: unknown, callback?: (error?: Error) => void) => void>,
data: unknown
): Promise<void> {
let error: Error | undefined
for await (const task of tasks) {
try {
if (task.length < 2) {
//sync
task.call(context, data)
} else {
await new Promise<void>((resolve, reject) => {
task.call(context, data, (error) => {
if (error) {
reject(error)
} else {
resolve()
}
})
})
}
} catch (e: unknown) {
error = e as Error
}
}
if (error) {
throw error
}
}

export class AsyncEventEmitter<T extends EventMap> extends EventEmitter {
emit<E extends keyof T>(event: E & string, ...args: Parameters<T[E]>) {
let [data, callback] = args
Expand All @@ -41,28 +71,7 @@ export class AsyncEventEmitter<T extends EventMap> extends EventEmitter {

// A single listener is just a function not an array...
listeners = Array.isArray(listeners) ? listeners : [listeners]

eachSeries(
listeners.slice(),
function (fn: any, next) {
let err

// Support synchronous functions
if (fn.length < 2) {
try {
fn.call(self, data)
} catch (e: any) {
err = e
}

return next(err)
}

// Async
fn.call(self, data, next)
},
callback
)
runInSeries(self, listeners.slice(), data).then(callback).catch(callback)

return self.listenerCount(event) > 0
}
Expand Down