ES8 Immediately invoked async function expression

Is this ‘a thing’?

Yes. It comes up every now and then, e.g. here. They’re known as IIAFEs 🙂
If you want to put focus on the arrow, you could also call them IIAAFs.

Are there pitfalls here I should be aware of?

Whenever you call a promise-returning function and don’t return the result to somewhere else, you are responsible for the promise yourself – which means that you have to handle errors from it. So the pattern should in general look like

(async () => {
    …
})().catch(err => {
    console.error(err);
});

if you don’t want to concern yourself with unhandled-rejection events.

What’s the lowdown on use of async/await in these kind of situations?

Not much, compared to the then version. However, you say “the external lib does not expect a return value from this callback“, which might hint at the library’s incompatibility with asynchronous callbacks, so beware what you are doing when. It also might depend on exceptions being thrown synchronously from the callback, so it all depends on what the library expects here (and if there are no expectations, whether that may change in the future). You don’t want future incompatibilities in case the library will start to treat promise return values specially.

However, I would still recommend the second pattern that directly passes the async function directly as the callback because of its better readability. If you want to avoid returning a promise to the library, create a helper function that wraps the callback:

function toVoid(fn) {
    return (...args) => void fn(...args);
}
function promiseToVoid(fn) {
    return (...args) => void fn(...args).catch(console.error);
}

which you could use like this:

chan.consume(queue, toVoid(async (msg) => {
     … // use `await` freely
}));

Leave a Comment