javascript - ReferenceError:函数未定义,从异步函数调用常规函数
问题描述
我收到以下错误:
ReferenceError: processElement is not defined
当试图从我的主异步函数调用这个常规函数时。
我正在使用 Chrome Puppeteer 来获取有关页面元素的信息。Puppeteer 想要在异步函数中运行,这是可以理解的,但我需要在其他函数中进行一些处理,可能是递归的。
我的基本结构是这样的:
function processElement(element, index) {
// element processing here, may ultimately need recursion.
}
function async main() {
// puppeteer stuff
const elements = document.querySelectorAll('p');
elements.forEach((element, index) => {
processElement(element, index);
}
}
main();
谢谢你的帮助!我是整个 async/await 范式的新手。
解决方案
您需要在 .async
之前使用关键字function
。
function processElement(element, index) {
// element processing here, may ultimately need recursion.
console.log(element);
}
async function main() {
// puppeteer stuff
const elements = document.querySelectorAll('p');
elements.forEach((element, index) => {
processElement(element, index);
});
}
main();
<p>Hello</p>
<p>World</p>
推荐阅读
- javascript - 如何使用 React 突出显示选项卡
- c# - 使用 rigibody.MovePosition 时,刚体不会与物体发生碰撞
- javascript - 使用命名集合展平嵌套的 json 数组
- mongodb - Spring Data MongoDB @DBRef 为子类加载 null
- javascript - 如何在 ASP.NET MVC 应用程序中测试客户端 JavaScript?
- javascript - Chrome 和 IE11 中用户定义的 window.close 函数行为之间的差异
- amazon-web-services - AWS Step Function:检查是否为空
- sql-server - 全局 SQL 连接对象
- html - 我正在尝试为每个导航项目获取不同的光标,但它只是在链接周围闪烁而不是完全显示
- html - 我如何将列表居中?