Zayonx
Zayonx

Reputation: 174

Undefined Variable in a variable after assignment

I am currently struggling in a way to get the variable "index" defined in the variable "name", it everytime returns "undefined" while it shouldn't. I know that i am i an async function but this case is weird and i cannot get it to work.

I have the following :

const puppeteer = require('puppeteer');


(async function main() {
    try {
        for (var index = 1; index < 20; index++) {
            console.log(index)
            const browser = await puppeteer.launch();
            const [page] = await browser.pages();

            await page.goto(`MYSITE`);

            var name = await page.evaluate(() => {
                return document.querySelector(`#itembanking-list > tbody > tr:nth-child(${index}) > td:nth-child(2)`).innerText;
            })

            await browser.close();
        }
    } catch (err) {
        console.error(err);
    }
})();

When running the following code, i am getting this error :

Error: Evaluation failed: ReferenceError: index is not defined

How can i get the variable "index" defined in "name" ?

Upvotes: 0

Views: 78

Answers (1)

Nickolay Kreshchenko
Nickolay Kreshchenko

Reputation: 44

You should pass the index variable as second param in evaluate and handle it in callback

await page.evaluate(index => {...code}, index)

Upvotes: 1

Related Questions