JS Event Handler: async function

You can call an async function from your EventListener.

The first problem I see is that you are invoking the callback function right away in the second argument of window.addEventListener by including it as loadEdit() instead of loadEdit or () => loadEdit(). You have to give it a function as second argument, right now you are giving a Promise or the return value of loadPre().

Try this way:

window.addEventListener("load", () => loadEdit(), false);

async function loadEdit() {
    // do the await things here.
}

Async function return Promises. So, if you would like to do something after loadEdit, try:

window.addEventListener("load", () => {
    loadEdit().then(/* callback function here */);
}, false);

async function loadEdit() {
    // do the await things here.
}

Leave a Comment