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

catching errors requires await even when calling synchronous functions #66

Closed
parthnaik opened this issue Oct 28, 2020 · 2 comments
Closed

Comments

@parthnaik
Copy link

parthnaik commented Oct 28, 2020

const Emittery = require('emittery')
const eventEmitter = new Emittery()

async function asyncFunction() {
    throw new Error('Async function error')
}

eventEmitter.on('callAsyncFunction', asyncFunction)

const runAsyncFunction = async() => {
    try {
        await eventEmitter.emit('callAsyncFunction')
    } catch(e) {
        console.log(e)
    }
}

runAsyncFunction() // Works as expected and prints 'Async function error'.


function syncFunction() {
    throw new Error('Sync function error')
}

eventEmitter.on('callSyncFunction', syncFunction) 

try {
    eventEmitter.emit('callSyncFunction') // Needs await if I want to catch the error even though it is calling a sync function to work as expected.
} catch(e) {
    console.log(e)
}
// Unhandled Promise Rejection. Requires await before eventEmitter.emit('callSyncFunction') even though calling sync function to allow it to catch the error.

Right now I am using the in-built node eventEmitter for synchronous functions and this one for async functions. If this is fixed, I can simply use this emitter and not use the in-built one at all.

@sindresorhus
Copy link
Owner

That's by design. Emittery is fully async even if the listener is not an async function.

@sindresorhus
Copy link
Owner

Duplicate of #48

@sindresorhus sindresorhus marked this as a duplicate of #48 Dec 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants