我使用puppeteer-cluster + node js。我是新来的。 麻烦了 我需要从站点获取XHR响应。我正在侦听页面,但是无法将结果值写入变量。我需要在代码的另一部分中使用该值。 如何等待函数在侦听器中执行并将结果写入变量?
dataCreation = [];
function get_data (data){
dataCreation [id] = data;}
await page.on('response', async (response) =>{
if (response.url === 'your_url'){
let XHR_response = await response.json();
let array_lenght = (XHR_response).length;
let data2 = XHR_response.objects[array_lenght-1].creationDate;
get_data(data2);}});
await console.log(dataCreation [id];
但是dataCreation [id]不败。因为我需要等待听众并从中获取结果。我该怎么做?谢谢。
答案 0 :(得分:1)
类似这样的东西:
const XHR_response = await new Promise((resolve) => {
page.on('response', checkResponse);
function checkResponse(response) {
if (response.url() === 'your_url') {
page.off('response', checkResponse);
resolve(response.json());
}
}
});
let array_lenght = XHR_response.objects.length;
let data2 = XHR_response.objects[array_lenght-1].creationDate;
get_data(data2);
console.log(dataCreation[id]);