我使用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是不可战胜的。因为我需要等待听众并从中得到结果。我该怎么做呢?谢谢你。
发布于 2020-11-05 15:52:29
如下所示:
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]);https://stackoverflow.com/questions/64689267
复制相似问题