I want to write numbers from an array into an HTML input in sequence. The values of the array inside my for..of loop return undefined only in the asynchronous operations. Here's my code:
const puppeteer = require('puppeteer');
const years = [2000,2001,2002];
(async () => {
const browser = await puppeteer.launch({
executablePath: './chromium/chrome.exe',
headless:false,
product:'chrome',
userDataDir: './cache'
});
const page = (await browser.pages())[0];
await page.setViewport({width:1920, height:1080});
await page.goto("https://www.immotop.lu/search/");
const example = async ()=> {
for (year of years){
await page.$eval('#search_form > div.filt-but-block > button.button-l3.filter-pan', el => el.click());
await page.$eval('#year_build', el => el.value = "" + year) // year is undefined here
}
}
example().then(() =>{
console.log('done');
})
})();
I think this is due to the synchronous looping through my array while executing asynchronous code with await, so the looping finished and the variable disappears before await is executed. Additionally I've heard that there should be a way to seperately save the variable in a function body, but so far I haven't figured out how to do it.
Here are the error messages:
(node:23492) UnhandledPromiseRejectionWarning: Error: Evaluation failed:
ReferenceError: year is not defined
(node:23492) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:23492) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.