为什么木偶不等?

时间:2020-09-30 17:48:06

标签: javascript node.js puppeteer

我的理解是,在await Promise.all(...)中,代码应按以下方式运行:

  1. 打印第一个console.log
  2. 等待9秒
  3. 打印最后一个console.log

如何使第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');
})

1 个答案:

答案 0 :(得分:4)

否,Promise.all(...)中的函数是同时运行的。这样做的目的是确保在代码继续之前所有问题都得到解决。返回值是按指定顺序给出的,但是函数本身会一次全部触发。

要按顺序运行异步功能,请使用.then()await

由于您唯一的异步功能是page.waitForconsole.log是同步功能),因此您只需执行以下操作:

console.log('printing before waiting 9 sec')
await page.waitFor(9000)
console.log('printing after waiting 9 sec')