0

I've been practising the following structure:

class ProductService extends EventEmitter {
    constructor() {
        super()
    }

    getProductById(id) {
        this.emit('beforeCall', { method: 'getProductById', params: { id }})
        return new Promise((resolve, reject) => {
            fetch(`/api/product/${id}`)
                .then((res) => {
                    this.emit('complete', { method: 'getProductById', params: { id }})
                    resolve(res)
                })
                .catch((err) => {
                    this.emit('error', { method: 'getProductById', params: { id }})
                    reject(err)
                })
        })
    }
}

Sample usage been:

const productService = new ProductService()

productService.on('beforeCall', (e) => {
    if (e.method === 'getProductById') {
        // getProductById method call detected!
        if(e.params.id === 123) {
            // getProductById(123) call detected!
        }
    }
})

productService.getProductById(123)
    .then((res) => {
        // product details fetched!
    })

This is all good and promotes event driven architecture, however I hope the event listeners can be more elegant.

I've might have seen usages where event emitter is binded to method oppose to object, usage will looks something like this:

const productService = new ProductService()
productService.getProductById(123)
    .on('beforeCall', (e) => {
        // getProductById(123) call detected!
    })
    .then((res) => {
        // product details fetched!
    })

Is that possible?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Trav L
  • 14,732
  • 6
  • 30
  • 39
  • 2
    I would look into `observables` instead of trying to make the `event emitter` work in the fashion you are wanting. – Tim Roberts Nov 15 '17 at 22:17
  • 1
    Based on what you've given, the above code is mixing the Tracking of an Asynchronous Function Call's Lifecycle with the actual Asynchronous Control Flow. Check out the [`async_hooks`](https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html#async_hooks_async_hooks) Library that was added to Node for tracking Asynchronous Resources in a Node App. More specifically, you should look at the [JS Embedder API](https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html#async_hooks_javascript_embedder_api) within `async_hooks` – peteb Nov 15 '17 at 22:30

0 Answers0