[英]jQuery proxy doesn't call async functions
I've found that I can't call async
functions with $.proxy
. 我发现我不能用
$.proxy
调用async
函数。 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. 我的情况是我代理了事件监听器,以便它们仍然具有相同的上下文,但是当我尝试代理
async
函数时,它就没有被调用 - 而且,没有抛出任何错误。
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. 当
async
关键字存在时,将不会调用该函数。 When you remove async
, it'll start working. 删除
async
,它将开始工作。
$('div').on('click', $.proxy(example, this));
async function example() {
console.log('test');
}
$.proxy
was awesome many years ago. $.proxy
很多年前很棒。 async/await is ES2017, and we already have bind
since ES5: async / await是ES2017,我们已经从ES5开始
bind
:
$('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. $.proxy
使用自定义$.isFunction
检查而不是普通typeof fn === 'function'
检查。 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. 这是因为本机异步函数是
AsyncFunction
实例,而不是Function
直接。
This is another reason why jQuery shouldn't always be used just because it can. 这是为什么jQuery不应该只是因为它可以使用的另一个原因。 jQuery helper functions were indispensable when there were no native alternatives or they were flaky - but aren't anymore.
当没有本地替代品或者它们是片状的时候,jQuery辅助函数是不可或缺的 - 但现在不再存在了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.