javascript JS 事件处理程序:异步函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50623279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS Event Handler: async function
提问by David E.
I'm building an app with Cordova. On one page, there is an EventListener that calls an async function. window.addEventListener("load", loadEdit(), false);
我正在用 Cordova 构建一个应用程序。在一个页面上,有一个调用异步函数的 EventListener。window.addEventListener("load", loadEdit(), false);
The function looks like this async function loadEdit(){...}.
该函数看起来像这样async function loadEdit(){...}。
When testing in the browser I get the following error even though the function is fully executed:
在浏览器中进行测试时,即使该功能已完全执行,我也会收到以下错误:
TypeError: Property 'handleEvent' is not callable.
类型错误:属性“handleEvent”不可调用。
However, if I change the EventListener to another function which then calls the async function, there seems to be no problem. For example:
但是,如果我将 EventListener 更改为另一个函数,然后调用异步函数,似乎没有问题。例如:
window.addEventListener("load", loadPre(), false);
...
function loadPre()
{
loadEdit();
}
- What is the problem with an async function getting called by the EventListener?
- Why does it not detect that the second method also calls an async function?
- EventListener 调用异步函数有什么问题?
- 为什么没有检测到第二种方法也调用了异步函数?
回答by skovmand
You can call an async function from your EventListener.
您可以从您的EventListener.
The first problem I see is that you are invoking the callback function right away in the second argument of window.addEventListenerby including it as loadEdit()instead of loadEditor () => loadEdit(). You have to give it a function as second argument, right now you are giving a Promise or the return value of loadPre().
我看到的第一个问题是,您正在window.addEventListener通过将其包含为loadEdit()而不是loadEditor来立即在第二个参数中调用回调函数() => loadEdit()。你必须给它一个函数作为第二个参数,现在你给的是一个 Promise 或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:
异步函数返回 Promise。因此,如果您想在 之后做某事loadEdit,请尝试:
window.addEventListener("load", () => {
loadEdit().then(// callback function here);
}, false);
async function loadEdit() {
// do the await things here.
}

