Search code examples
javascriptpromiseasync-awaitevent-handlingcatch-block

How to handle an async function called by an event?


Let's say I have async function named 'Main' that gets called during page load like this:

window.addEventListener('load', Main);

Since Main is an async function, I'd like to catch errors from its promise chain by appending .catch((e)=>{ console.error(e);});. However, I don't think that plays nice with window.addEventListener (which returns undefined) and expects only the function's assignment as the 2nd argument.

Is it possible to handle promise rejections of Main without creating a wrapper function?


Solution

  • You have two options:

    1. Use a wrapper function, or

    2. Handle all errors within Main using try/catch

    For instance:

    window.addEventListener("load", evt => {
        Main(evt).catch(err => {
            //...handle/report error...
        });
    });
    

    or in Main:

    async function Main(evt) {
        try {
            // ...your logic...
        } catch (e) {
            //...handle/report error...
        }
    }
    

    In both cases, make sure the "handle/report error" code itself never throws an error. :-)