首页 > 解决方案 > 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 范式的新手。

标签: javascriptnode.jsasync-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>


推荐阅读