I've found that I can't call async
functions with $.proxy
. My case was that I proxied event listeners so that they'd still have the same context, but as soon as I tried proxying to an async
function, it just didn't get called - also, no errors were thrown.
Could anyone explain me why this doesn't work?
The simple example below will allow you to reproduce the issue. When the async
keyword is there, the function will not be called. When you remove async
, it'll start working.
$('div').on('click', $.proxy(example, this));
async function example() {
console.log('test');
}
$.proxy
was awesome many years ago. async/await is ES2017, and we already have bind
since ES5:
$('div').on('click', example.bind(this));
So we have async arrows:
const example = async () => {
console.log('test');
}
$.proxy
uses custom $.isFunction
check instead of plain typeof fn === 'function'
check. This results in false negative for native async functions (transpiled async vs native async). This results from the fact that native async functions are instances of AsyncFunction
, not Function
directly.
This is another reason why jQuery shouldn't always be used just because it can. jQuery helper functions were indispensable when there were no native alternatives or they were flaky - but aren't anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With