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

Callbacks in class must be promises #20

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
93 changes: 93 additions & 0 deletions src/__tests__/event.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { threadedClass, ThreadedClassManager } from '..'
// import { EventEmitter } from 'events'

describe('EventEmitter', () => {
beforeEach(async () => {
await ThreadedClassManager.destroyAll()
expect(ThreadedClassManager.getThreadCount()).toEqual(0)
})
afterEach(async () => {
await ThreadedClassManager.destroyAll()
expect(ThreadedClassManager.getThreadCount()).toEqual(0)
})

// test('non-threadedclass emit', () => {
// const em = new EventEmitter()
// em.on('test', () => {
// throw new Error('abc')
// })

// try {
// em.emit('test')
// } catch (e) {
// // Finish here
// return
// }
// // Should end in the catch
// expect(false).toBeTruthy()
// })
// test('threadedclass emit', async () => {
// // class EventEmitterExt extends EventEmitter {
// // doEmit (str: string) {
// // this.emit(str)
// // }
// // }
// const em2 = await threadedClass<EventEmitter>('./nope.js', EventEmitter, [], {
// disableMultithreading: true
// })
// console.log('init')

// await em2.on('nope', console.log)

// await em2.on('test', (a: any, b: any) => {
// console.log('on', a, b)
// throw new Error('abc')
// })

// console.log('register')

// try {
// await em2.emit('test', 1, 5)
// } catch (e) {
// // Finish here
// return
// }
// // Should end in the catch
// expect(false).toBeTruthy()
// })

class FakeClass {
basicFcn (cb: () => number) {
// An example function that is not aware it might want to be run in a threadedClass
return cb() + 5
}

async promiseFcn (cb: () => Promise<number>) {
// This function is safe for threaded class, as its callback returns a promise
return await cb() + 5
}
}

test('class promise-callback', async () => {
const em2 = await threadedClass<FakeClass>('../../test-lib/house.js', FakeClass, [], {
disableMultithreading: true
})

const callback = () => 10

const res = await em2.promiseFcn(callback)
expect(res).toEqual(15)
})
test('class normal-callback', async () => {
const em2 = await threadedClass<FakeClass>('../../test-lib/house.js', FakeClass, [], {
disableMultithreading: true
})

const callback = () => 10

const res = await em2.basicFcn(callback)
expect(res).toEqual(15)
})


})