Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery proxy doesn't call async functions

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');
}
like image 369
macbem Avatar asked Mar 08 '23 12:03

macbem


1 Answers

$.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.

like image 176
Estus Flask Avatar answered Mar 11 '23 03:03

Estus Flask