I have the following set up in my code where the user chooses a basic puppeteer script in the node.js terminal which then should fully execute. After it's done the user should get the 'main menu' again. Also some scripts require extra input.
But when I execute the script it does initially wait for the users input but then doesn't wait for the puppeteer script to end before returning to the 'main menu'
How should I properly use async functions to make this work? I've looked it up but couldn't get much further with it.. Thnx in advance!
Example script:
const console = require('console');
const puppeteer = require('puppeteer');
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
async function function1() {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setViewport({ width: 1280, height: 800 })
await page.goto('https://www.nytimes.com/')
await page.screenshot({ path: 'nytimes.png', fullPage: true })
await browser.close()
}
async function function2() {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setViewport({ width: 1280, height: 800 })
await page.goto('https://www.nytimes.com/')
await page.screenshot({ path: 'nytimes.png', fullPage: true })
await browser.close()
}
async function function3(address, location) {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setViewport({ width: 1280, height: 800 })
await page.goto(address)
await page.screenshot({ path: location, fullPage: true })
await browser.close()
}
function Main() {
console.log('What script do you want to use?');
console.log("script 1 -> '1'");
console.log("script 1 -> '2'");
console.log("script 1 -> '3'");
console.log("EXIT -> 'x'");
rl.question('Choice: ', (answer) => {
if (answer == "1")
{
function1().then(Main());
}
else if (answer == "2")
{
function2().then(Main());
}
else if (answer == "3")
{
rl.question('Choice: ', (address) => {
rl.question('Choice: ', (location) => {
function3(address, location).then(Main());
});
});
}
else if (answer == "x")
{
rl.close();
process.exit();
}
else
{
console.log("Pick an option!");
Main();
}
});
}
Main();
Specify Main without the parentheses in the Promise chain:
function Main() {
if (...) {
function1().then(Main) // ✅
}
...
}
Alternatively, Main could be an async function:
async function Main() {
if (...) {
await function1()
} else if (...) {
await function2()
} else {
rl.close()
return process.exit()
}
Main()
}