Javascript Node.js将变量从事件处理程序返回到父函数

Javascript Node.js将变量从事件处理程序返回到父函数,javascript,node.js,puppeteer,Javascript,Node.js,Puppeteer,我需要函数scrape返回在页面中获得的值。on(“请求”)事件处理程序 async function scrape(url) { const page = await browser.newPage(); await page.setRequestInterception(true); page.on("request", async(request) => { return "fish" }

我需要函数
scrape
返回在
页面中获得的值。on(“请求”)
事件处理程序

async function scrape(url) {
        const page = await browser.newPage();
        await page.setRequestInterception(true);

        page.on("request", async(request) => {
            return "fish"
        }
        await page.goto(url)
    }
目前:

const ans = await scrape(url)
console.log(ans)
"undefined'
预期:

const ans = await scrape(url)
console.log(ans)
"fish"
尝试如下操作:

async function scrape(url) {
    let sendRequest = []
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.setRequestInterception(true)
    page.on('request', request => {
      request.continue()
      sendRequest.push('fish')
    })
    await page.goto(url)
    return sendRequest
}

使用for continues请求和可选请求覆盖。要使用此功能,应使用启用请求拦截。如果未启用请求拦截,将立即引发异常。

您将需要返回承诺,当您看到正在等待的事件时,该承诺将得到解决

const matchRequest = request => request.method() === 'GET'; // your filter
async function scrape(url) {
  return new Promise(resolve => {
    const page = await browser.newPage();
    // not sure what your logic is, but if you don't need to cancel or modify requests/resposes you probably don't need interception
    // await page.setRequestInterception(true);
    page.on("response", async(response) => {
        if (matchRequest(response.request())) {
           resolve(response.buffer());
        }
    }
    await page.goto(url);
  })
}

const body = await scrape('https://example.com');

为什么你会期望
?fish是从页面返回的。在回调时,您根本不会返回函数scrape中的任何内容-我建议您在
页面上做出承诺。。。e、 g.
returnnewpromise(resolve=>{page.on(“request”,request=>{resolve(“fish”);})-不过,这可能是一种不好的做法,若页面从未发出“请求”怎么办!你为什么这么想?@JaromandaX你的建议在我调整了一点后奏效了。感谢您指出这种方法的缺点。我将编写一些代码来处理此类错误情况。再次感谢<代码>在我调整了一点之后
-真的吗?我的代码出了什么问题:pHaha…没错,比如说,我只需要使promise的解析函数异步:
返回新的promise(async(resolve).
,因为我在其中运行另一个异步函数