在 jQuery .ready() 中使用 ES2017 异步 [英] Using ES2017 async with jQuery .ready()
问题描述
我正在学习 异步函数 功能在 ES2017 中引入,但我似乎无法使以下内容起作用:
I'm learning about the async function feature introduced in ES2017, and I couldn't seem to get the following to work:
async function sayHelloAsync() {
let {autosave} = await browser.storage.local.get('autosave');
if (autosave) {
$('#helloButton').click();
}
}
$(sayHelloAsync);
我在我的小型应用程序中为我的需求管理了一个解决方法,但我想知道为什么这不起作用.一旦我删除 async
,它就会按预期工作.我还有其他自定义事件绑定,它们使用 async
函数作为回调,它们工作得很好.
I have managed a workaround for my needs in my small application, but I'm wondering why this would not work. As soon as I remove the async
, it works as expected. I also have other custom event bindings which use async
functions as callbacks, and they work just fine.
我在 Linux 上使用 Google Chrome 57.
I am using Google Chrome 57 on Linux.
更新
我更新了我的代码示例,以消除关于我需要加载的 DOM 和 jQuery 的困惑.
I updated my code sample to remove the confusion about my need for loaded DOM and jQuery.
推荐答案
我已经检查了 jQuery
源代码,这里是它执行的检查以找出参数是什么:
I have checked jQuery
source code and here is a check it performs to find out what the argument is:
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
}
并且 jQuery.type( obj )
返回 object
而不是 function
预期的.这可能是 jQuery
中的一个错误,但这就是函数没有执行的原因.
And jQuery.type( obj )
returns object
not function
as expected. That's probably a bug in jQuery
, but that's why the function is not executed.
再挖一点,jQuery
调用 toString.call( obj )
来确定一个类型并尝试将结果映射到已知类型.它不能,这就是它返回 object
的原因.
Dug a bit more and jQuery
calls toString.call( obj )
ti determine a type and tries map the result to known type. It cannot and that's why it returns object
.
所以这里的问题在于 jQuery
而不是你的异步函数.
So the problem here is with jQuery
not with your async function.
这篇关于在 jQuery .ready() 中使用 ES2017 异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!