Looks like global variables dont change according to changes made inside functions

21 Views Asked by At

Assume this code:


const puppeteer = require('puppeteer');
const express = require('express')

const app = express()
app.use(express.json())

let browser = undefined;
let page = undefined;

let type = async ( selector, typeString) => {
    await page.waitForSelector(selector)
   //...
}

let setup = async function () {
    browser = await puppeteer.launch({headless: false});
    page = await browser.newPage();
   //...
}
app.post ('/login',  (req, res) => {
    console.log("/login", " req.body: ",req.body)
    setup()
    console.log(page) //undefined
    type(usernameInputSelector, req.body.username)
    type( passwordInputSelector,req.body.password)
    res.end() 
})
//...

I send an http request to fire app.post callback. I am trying to figure out how comes that after setup() , page remains undefined even though setup defines it and sets a value, later when I use type() , the program crashes because page is undefined.

I tried to delete setup() function and instead just copy paste its content into the app.post(), and it works! I assume its something with scoping, but not sure what it is.

0

There are 0 best solutions below