我的理解是,在await Promise.all(...)
中,代码应按以下方式运行:
如何使第3条打印语句在9秒后而不是立即打印?
实际发生的情况
await Promise.all(...)
中的所有语句是同时执行的,而不是顺序执行的。
(async () => {
const browser = await puppeteer.launch({headless:false, slowMo:100});
const page = await browser.newPage();
await page.goto('https://google.com', {waitUntil: 'networkidle2'});
await Promise.all(
[
console.log('printing before waiting 9 sec'),
page.waitFor(9000),
console.log('printing after waiting 9 sec')
]
);
//await browser.close();
})().catch((error) =>{
console.error("the message is " + error.message);
});
app.listen(3000, function (){
console.log('server started');
})
答案 0 :(得分:4)
否,Promise.all(...)中的函数是同时运行的。这样做的目的是确保在代码继续之前所有问题都得到解决。返回值是按指定顺序给出的,但是函数本身会一次全部触发。
由于您唯一的异步功能是page.waitFor
(console.log
是同步功能),因此您只需执行以下操作:
console.log('printing before waiting 9 sec')
await page.waitFor(9000)
console.log('printing after waiting 9 sec')