I have a Node.js application which is connected to MongoDb. I am retrieving a certain json from my mongodb collection using findOne() so the value is obtained in a callback. My application also has browser automation tasks using puppeteer. To fill in a certain input field I am trying to use the json that I retrieved from mongodb collection. But due to the asynchronous nature I am unable to use the callback value outside the function. I need to use the callback value to send as an input for the puppeteer.
I have tried to fetch the value from findOne() callback using another function but still unable to use it for the puppeteer async function.
The below code fetches the value from mongodb:
var g;
db.collection("users").findOne({}, function(err, result) {
if (err) throw err;
storedata(result);
});
function storedata (x){
g = x;
//console.log(g);
}
Puppeteer code:
(async () => {
const browser = await puppeteer.launch({
headless: false
})
const page = await browser.newPage();
await page.goto('http://0.0.0.0:4200/')
await page.$eval('[placeholder="BPMN xml"]', el => {
return el.value = g
})
})()
I always get the error g is not defined. Of course, I understand that scope of g is within the function but even when I tried to place the puppeteer code inside the function storedata() I get g undefined error. Kindly help me in understanding the callback values in a better way.
gdefined? It's nowhere in your code.