I'm using nodeJS. I want to wait for a property inside an object to become true, and then continue code execution.
Here's what my code looks like:
export async function createRun() {
try {
let shared = { url: "", device: "", finished: new Promise(() => {}) };
const browser = await launch();
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(0);
await page.setBypassCSP(true);
await page.exposeFunction(
"onMessageReceivedEvent",
async (e: { type: string; data: Message }) => {
if (e.data === "finished") {
shared.finished = ;
}
}
);
const listenFor = (type: string) => {
return page.evaluateOnNewDocument((type: any) => {
window.addEventListener(type, (e) => {
// @ts-ignore
window.onMessageReceivedEvent({ type, data: e.data });
});
}, type);
};
await listenFor("message");
console.log('before');
// wait for shared.finished to become true
// continue execution
console.log('after')
}
How can this be implemented? Thanks in advance!
If you do need to go this way, you can try something like this (sorry, I do not know TS):
export async function createRun() {
try {
let resolver;
let shared = { url: "", device: "", finished: new Promise((resolve) => { resolver = resolve; }) };
const browser = await launch();
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(0);
await page.setBypassCSP(true);
await page.exposeFunction(
"onMessageReceivedEvent",
async (e: { type: string; data: Message }) => {
if (e.data === "finished") {
resolver();
}
}
);
const listenFor = (type: string) => {
return page.evaluateOnNewDocument((type: any) => {
window.addEventListener(type, (e) => {
// @ts-ignore
window.onMessageReceivedEvent({ type, data: e.data });
});
}, type);
};
await listenFor("message");
console.log('before');
await shared.finished;
// continue execution
console.log('after')
}
However, page.waitForFunction() can be simpler solution, as suggested in the comment.