【发布时间】:2021-11-02 11:18:25
【问题描述】:
目前正在处理一个涉及 Puppeteer 库的小型 NodeJS 项目。我遇到的问题是 index.js 中的 main() 函数似乎永远不会退出。所有代码都运行良好,但在 VS 代码中看起来程序仍在运行。
下面的一些示例代码:
var UserAgent = require('user-agents');
const userAgent = new UserAgent();
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());
class TS {
constructor() {
let page;
}
async init() {
const browser = await puppeteer.launch({ headless: false });
this.page = await browser.newPage();
await this.page.setUserAgent(userAgent.toString());
}
}
async function main(params) {
console.log("Started main..");
const ts = new TS();
await ts.init();
console.log("Ending main..");
}
main().catch(e => console.error(e));;
如果我在 VS 代码终端中运行上述代码,输出将显示:
开始主.. 结束主.. (空行)
程序现在将无限期地保持这种状态,直到我按 ctrl + C。如果我删除等待的 ts.init() 调用,那么它会按预期工作并且我的终端会显示
开始主.. 结束主.. PS C:\Users\username\Desktop\nodejs-projects\my-project>
谁能解释这里发生了什么?
在我所做的所有研究中,我能想到的最好的结果是事件循环存在一些问题,尽管真的不知道是什么原因造成的。
使用类似的方法将 .then() 添加到 main() 可以解决问题
.then(() => {
setTimeout(() => {
process.exit(0);
}, 5000);;
})
这证明了自从调用了 setTimeout() 以来,promise 正在解决。但是,如果 main 解析并且没有代码可以运行,我会非常迷茫,为什么程序不会在不调用 process.exit() 的情况下自动结束。非常感谢一些帮助。
【问题讨论】:
标签: javascript node.js asynchronous puppeteer main