I use puppeteer-cluster + node js. I am new in that. I have some trouble. I need to get XHR response from site.I am listening to the page, but I cannot write the resulting value to the variable. I need to use the value in another part of the code. how to wait for the function to execute in a listener and write the result to a variable?
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];
But dataCreation [id] is undefeated. Because i need to await listener and get result from it. How can I do it? Thank you.
Something like this:
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]);