【问题标题】:nodejs not waiting for puppeteer to finishnodejs 不等待 puppeteer 完成
【发布时间】:2022-01-17 01:25:21
【问题描述】:

我在我的代码中设置了以下设置,用户在 node.js 终端中选择一个基本的 puppeteer 脚本,然后应该完全执行。完成后,用户应该再次获得“主菜单”。还有一些脚本需要额外的输入。

但是当我执行脚本时,它最初会等待用户输入,但不会等待 puppeteer 脚本结束,然后返回“主菜单”

我应该如何正确使用异步函数来完成这项工作?我已经查过了,但无法进一步了解它。提前谢谢!

示例脚本:

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();

【问题讨论】:

  • .then(Main()) 是错误的。结果为.then(undefined)。你会想要.then(() => Main())。不确定是否能解决您的问题,但这是正确的语法。

标签: javascript node.js async-await puppeteer


【解决方案1】:

在 Promise 链中指定不带括号的 Main

function Main() {
  if (...) {
    function1().then(Main) // ✅
  }
  ...
}

或者,Main 可以是异步函数:

async function Main() {
  if (...) {
    await function1()
  } else if (...) { 
    await function2()
  } else {
    rl.close()
    return process.exit()
  }

  Main()
}

【讨论】:

    猜你喜欢
    • 2019-12-13
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2022-07-27
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多