[英]Node.js Return variable from event handler to parent function
I need the function scrape
to return the value obtained in the page.on("request")
event handler. 我需要函数
scrape
返回在page.on("request")
事件处理程序中获得的值。
async function scrape(url) {
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on("request", async(request) => {
return "fish"
}
await page.goto(url)
}
Currently: 目前:
const ans = await scrape(url)
console.log(ans)
"undefined'
Expected: 预期:
const ans = await scrape(url)
console.log(ans)
"fish"
you'll need to return promise that is resolved when you see event that you are waiting 您需要返回看到正在等待的事件时已解决的承诺
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');
Try follow like: 尝试按照以下步骤操作:
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
}
Using request.continue()
for continues request with optional request overrides. 使用
request.continue()
通过可选的请求覆盖继续请求。 To use this, request interception should be enabled with page.setRequestInterception
. 要使用此功能,应使用
page.setRequestInterception
启用请求拦截。 Exception is immediately thrown if the request interception is not enabled. 如果未启用请求拦截,则会立即引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.