在回调中访问外部范围变量
Accessing outer scope variable in callback
我在 Puppeteer 中有这个 ES6 代码:
async function waitForSelectorReversed(page, selector) {
await page.waitFor(() => !document.querySelector(selector));
}
当我调用此代码时出现错误 Evaluation failed: ReferenceError: selector is not defined
。我知道这个错误是由于闭包内的代码无法从外部范围访问变量引起的。有什么方法可以让它发挥作用?
您需要将外部作用域变量显式传递给 page.waitFor
才能正常工作。正如 documentation 所述:
To pass arguments from node.js to the predicate of page.waitFor
function:
const selector = '.foo';
await page.waitFor(selector => !document.querySelector(selector), {}, selector);
对于您的代码,您只需删除第一行,因为 selector
已经定义。
这与其说是普通的 Javascript 或 ES6 的东西,不如说是 Puppeteer(和类似 Puppeteer 的工具)在与页面交互时如何工作的怪癖。
我在 Puppeteer 中有这个 ES6 代码:
async function waitForSelectorReversed(page, selector) {
await page.waitFor(() => !document.querySelector(selector));
}
当我调用此代码时出现错误 Evaluation failed: ReferenceError: selector is not defined
。我知道这个错误是由于闭包内的代码无法从外部范围访问变量引起的。有什么方法可以让它发挥作用?
您需要将外部作用域变量显式传递给 page.waitFor
才能正常工作。正如 documentation 所述:
To pass arguments from node.js to the predicate of
page.waitFor
function:const selector = '.foo'; await page.waitFor(selector => !document.querySelector(selector), {}, selector);
对于您的代码,您只需删除第一行,因为 selector
已经定义。
这与其说是普通的 Javascript 或 ES6 的东西,不如说是 Puppeteer(和类似 Puppeteer 的工具)在与页面交互时如何工作的怪癖。