在 Node 中同步打印.js使用 Puppeteer



我正在尝试在 Node.js 中编写同步代码。

function func1(fn) { 
const puppeteer = require('puppeteer');
var If = require('If');
var async = require("async");
(async () => {

const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
// Open page.
await page.goto("https://www.google.com/");
})();
fn();
}
func1(function(){ 
console.log('world');
}); 

我希望首先打开Google页面,当我关闭它时,程序应该打印:world

在断开连接的木偶事件的回调中调用您的fn
下面的代码对我来说效果很好:

function func1(fn) {
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
// Open page.
await page.goto("https://www.google.com/");
browser.on('disconnected', () => {
fn();
});
})();
}
func1(function(){
console.log('world');
});

你可以使func1异步,然后你可以await你的内部匿名异步函数:

async function func1 (fn) {
const puppeteer = require('puppeteer');
var If          = require('If');
var async       = require('async');
await (async () => {
const browser = await puppeteer.launch({headless: false});
const page    = await browser.newPage();
await page.goto('https://www.google.com/');
})();
fn();
}
func1(function () {
console.log('world');
});

相关内容

  • 没有找到相关文章

最新更新