我正在尝试通过回调调用map函数。 但是我无法通过以下错误消息调用回调函数。
> tsc && node index.js
(node:17460) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: translateText is not defined
at mapFunc (__puppeteer_evaluation_script__:3:13)
at Array.map (<anonymous>)
at __puppeteer_evaluation_script__:13:22
at ExecutionContext.evaluateHandle (C:\github\dojo-tools\node_modules\puppeteer\lib\ExecutionContext.js:121:13)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at ExecutionContext.<anonymous> (C:\github\dojo-tools\node_modules\puppeteer\lib\helper.js:110:27)
at ExecutionContext.evaluate (C:\github\dojo-tools\node_modules\puppeteer\lib\ExecutionContext.js:48:31)
at ExecutionContext.<anonymous> (C:\github\dojo-tools\node_modules\puppeteer\lib\helper.js:111:23)
at ElementHandle.$$eval (C:\github\dojo-tools\node_modules\puppeteer\lib\JSHandle.js:453:50)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at ElementHandle.<anonymous> (C:\github\dojo-tools\node_modules\puppeteer\lib\helper.js:110:27)
at getHTML (C:\github\dojo-tools\index.js:77:32)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:17460) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17460) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我想在回调函数中调用外部函数。 因为我想处理每个数组项。
下面是我当前的代码。
function translateText() {...}
async function getHTML() {
const browser = await puppeteer.launch({
headless: false
});
const func = (nodes: Array<Element>) => {
const mapFunc = (n: Element) => {
translateText(n.textContent || "NO STRING"); // <-------- ERROR
switch (n.tagName) {
case 'P':
return ` * ${n.textContent}`;
case 'LI':
return ` * ${n.textContent}`;
default:
return ` * COULDNOT ANALYZE - ${n.textContent}`;
}
}
return nodes.map(mapFunc);
}
const page = await browser.newPage();
await page.goto('https://azure.microsoft.com/en-us/updates/the-azure-us-gov-iowa-region-is-being-retired-april-30-2020/'); // 表示したいURL
const elm = await page.$('#main > div > div:nth-child(3) > div > div:nth-child(1)');
if (elm !== null) {
const data = await elm.$$eval('p, li', func);
console.log(data);
}
browser.close();
}
能否让我知道如何在地图回调函数中访问外部函数?
答案 0 :(得分:2)
看起来像elm.$$eval('p, li', func)
在浏览器上下文中评估func
。因此,没有简单的方法可以调用外部函数。简单的解决方案是使translateText
的{{1}}内部功能。