ProtocolError: Protocol error (Runtime.callFunctionOn): Target closed. - express.js and puppeteer-cluster - express

I want to iterate over key-pairs of data.extractRules and get elements data from the page.
This snippet inside forEach loop is causing app crashes. I tried hardcoding key and cssSelector and tried this outside of forEach loop and it worked.
const extractContent = {};
if (data.extractRules !== null) {
Object.entries(data.extractRules).forEach(async ([key, cssSelector]) => {
extractContent[key] = await page.$$eval(cssSelector, (elements) =>
elements.map((element) => element.outerHTML)
);
});
}

I figured out solution 😁
async function getSelectorContent(page, cssSelector) {
return page.$$eval(cssSelector, (elements) =>
elements.map((element) => element.outerHTML)
);
}
const extractContent = {};
if (data.extractRules !== null) {
await Object.entries(data.extractRules).reduce(
async (item, [key, cssSelector]) => {
await item;
extractContent[key] = await getSelectorContent(page, cssSelector);
},
Promise.resolve()
);
}

Related

Async function react native

We have to create a Bingo game in React Native with Firebase Realtime Database on Android simulator. The app game is for 2 players. When the first player enter in the app, he create the game and wait for the second player to join.
we want to create a screen with the writing: "Waiting for another player" that appears to the first player until the second player connects then when the second player connects the card is shown.
We wrote this code but it return 'undefined' .
function Game(){
const authCtx = useContext(AuthContext);
const gameCtx = useContext(GameContext);
const [loadPlayer, setLoadPlayer] = useState(false);
useEffect(() => {
async function gamePlay(){
gameCtx.player1 = authCtx.token;
const play = await setGame(authCtx.token, gameCtx);
console.log(play); //return undefined
if(play == 'CREATE'){
setLoadPlayer(true);
}else if(play == 'UPDATE'){
setLoadPlayer(false);
}
if(loadPlayer){
return <LoadingOverlay message="Waiting for another player... " />;
}
}
gamePlay();
}, []);
return <Card />;
}
export default Game;
export function create(game){
const db = getDatabase();
const newGameKey = push(child(ref(db), 'GAME')).key;
set(ref(db, '/GAME/' + newGameKey), game)
.then(() => {console.log('Game Create!');})
.catch((error) => {console.log(error);});
}
export function setGame(email, game){
const dbRef = ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}
export function updateGame(email, key){
console.log('Update: ' + key);
const db = getDatabase();
const updates = {};
updates['/GAME/' + key + '/player2'] = email;
return update(ref(db), updates);
}
We think this is due to "async" and "await" because not working correctly.
Do you have any suggestions?
How can we redirect the first player to a waiting screen?
is ref(getDatabase()) is promise?. if it is then use await before it.
and use async function before setGame if you are using await while calling.
export async function setGame(email, game){
const dbRef = await ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}

How do I resolve a callback error with 'callback' is an instance of Object)?

TypeError: callback is not a function. (In 'callback(data)',
'callback' is an instance of Object)
The code here works just fine when I write it like this:
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
// { categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
When i uncomment that other line, it breaks and gives me this error.
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
{ categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
Here is the relevant snippet from listingsAPI (below) if it helps but this code works fine when there is only one object. Is there a specific way to make this work with two objects like above?
if (categoryId) {
return (
listingsRef
.where('categoryID', '==', categoryId)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
if (categoryId2) {
return (
listingsRef
.where('categoryID2', '==', categoryId2)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
You can combine your queries via this way if you want to have it optional:
let query = listingsRef.where('isApproved', '==', isApproved)
if (categoryId) {
query = query.where('categoryID', '==', categoryId)
}
if (categoryId2) {
query = query.where('categoryID2', '==', categoryId2)
}
query.onSnapshot...

$nextTick running before previous line finished

I have a vue function call which is triggered when selecting a radio button but it seems that my code inside my $nextTick is running before my previous line of code is finished. I don't want to use setTimout as I don't know how fast the user connection speed is.
findOrderer() {
axios.post('/MY/ENDPOINT')
.then((response) => {
this.orderers = response.data.accounts;
console.log('FIND_ORDER', this.orderers)
...OTHER_CODE
}
rbSelected(value) {
this.findOrderer();
this.newOrderList = [];
this.$nextTick(() => {
for (var i = 0, length = this.orderers.length; i < length; i++) {
console.log('FOR')
if (value.srcElement.value === this.orderers[i].accountType) {
console.log('IF')
this.newOrderList.push(this.orderers[i]);
}
}
this.$nextTick(() => {
this.orderers = [];
this.orderers = this.newOrderList;
console.log('orderers',this.orderers)
})
})
}
Looking at the console log the 'FINE_ORDERER' console.log is inside the 'findOrderer' function call so I would have expected this to be on top or am I miss using the $nextTick
That's expected, since findOrderer() contains asynchronous code. An easy way is to simply return the promise from the method, and then await it instead of waiting for next tick:
findOrderer() {
return axios.post('/MY/ENDPOINT')
.then((response) => {
this.orderers = response.data.accounts;
console.log('FIND_ORDER', this.orderers);
});
},
rbSelected: async function(value) {
// Wait for async operation to complete first!
await this.findOrderer();
this.newOrderList = [];
for (var i = 0, length = this.orderers.length; i < length; i++) {
console.log('FOR')
if (value.srcElement.value === this.orderers[i].accountType) {
console.log('IF')
this.newOrderList.push(this.orderers[i]);
}
}
this.orderers = [];
this.orderers = this.newOrderList;
console.log('orderers',this.orderers)
}

setinterval function is running infinitely

const interval = setInterval(() => {
fire.database().ref().child(getpath())
.once("value",
(snapshot) => {
let item = snapshot.val()
console.log(item)
if (item !== null) {
let array = [];
Object.
keys(item)
.forEach(i => array.push(item[i]));
setCard1(array);
}
console.log(item, "item")
if (item !== null) {
itemlen = 7 //length of object I get from valid result
//stop polling for results
console.log(itemlen, "should clear")
}
else {
console.log("polling")
}
})
}, 1000)
console.log("comingout")
if (itemlen !== 0) {
console.log("goingIn")
clearInterval(interval);
}
}, [prefVar]);
expected clearinterval to stop the setinterval function but it is running continuosly and not stopping
itemlen is getting non zero values.Is there a better way of implementing this ?
I want stop useEffect once I get valid value from db.My code inside the for setinterval selects a random path and retrieve that path only problem is that sometimes the path is empty,thus using setInterval
I would create two state items, one which keeps the interval and the other which stores itemlen, and would use another useEffect to listen on changes to itemlen, and when it is not 0, the interval should clear. Also, I would check if there is another interval running before you start another one.
const [itemlen, setItemlen] = useState(0);
const [pollingInterval, setPollingInterval] = useState(null);
useEffect(() => {
if (pollingInterval === null) {
setPollingInterval(setInterval(() => {
fire.database().ref().child(getpath())
.once("value",
(snapshot) => {
let item = snapshot.val()
console.log(item)
if (item !== null) {
let array = [];
Object.
keys(item)
.forEach(i => array.push(item[i]));
setCard1(array);
}
console.log(item, "item")
if (item !== null) {
setItemlen(7);
console.log("should clear")
} else {
console.log("polling")
}
})
}, 1000));
}
}, [prefVar]);
useEffect(() => {
if (itemlen !== 0 && pollingInterval !== null) {
clearInterval(pollingInterval);
setPollingInterval(null);
}
}, [itemlen])

Primeng loading icon is not updating

I am using primeng turbo table with lazy loading and enabled loading to attribute it's not getting updated even got updated
<p-table #dt [loading]="loader" [columns]="cols" [value]="datasource.merchants" [rows]="perPage" [paginator]="true" [pageLinks]="5"
[lazy]="true" [totalRecords]="datasource.totalCount" (onLazyLoad)="loadLazyData($event)" [exportFilename]="'merchant-list'">
.....
Script
loadLazyData(event: LazyLoadEvent) {
if (event.first !== this.searchParams.offset || event.rows !== this.searchParams.limit) {
this.loader = true;
this.searchParams.offset = event.first;
this.searchParams.limit = event.rows;
this.apiService.getResponse(this.smartSearchParams.query, event.first, event.rows)
.subscribe((result) => {
this.datasource = result;
let newArray = result.merchants.slice();
this.dataTable.value = newArray;
setTimeout(() => {
this.loader = false;
this.dataTable.loading = this.loader;
});
}, (err: any) => {
setTimeout(() => {
this.loader = false;
this.dataTable.loading = this.loader;
});
});
}
can someone help me with this issue
The issue is with changeDetection for the component.
I have removed the changeDetection:ChangeDetectionStrategy.OnPush from my component its started working