【问题标题】:ReferenceError: function is not defined, calling regular function from async function [duplicate]ReferenceError:未定义函数,从异步函数调用常规函数[重复]
【发布时间】:2019-06-20 05:01:15
【问题描述】:

我收到以下错误:

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 范式的新手。

【问题讨论】:

  • 能否请您发布您的实际代码,而不是语法错误?
  • 您是否使用 Puppeteer 来评估加载页面中的代码?
  • Puppeteer 不支持闭包。

标签: javascript node.js async-await


【解决方案1】:

您需要在function 之前使用async 关键字。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多