node.js - Chrome 远程接口(interface)的异步/等待问题

标签 node.js async-await

我想测试这段代码并等到它完成后再断言结果。不确定问题出在哪里,它应该在最后返回 Promise.resolve(),但在执行代码之前记录 end

Page.loadEventFired 前面是否也应该有 await

const CDP = require('chrome-remote-interface')

async function x () {
  const protocol = await CDP()

  const timeout = ms => new Promise(resolve => setTimeout(resolve, ms))

  // See API docs: https://chromedevtools.github.io/devtools-protocol/
  const { Page, Runtime, DOM } = protocol
  await Promise.all([Page.enable(), Runtime.enable(), DOM.enable()])

  Page.navigate({ url: 'http://example.com' })

  // wait until the page says it's loaded...
  return Page.loadEventFired(async () => {
    console.log('Page loaded! Now waiting a few seconds for all the JS to load...')
    await timeout(3000) // give the JS some time to load

    protocol.close()

    console.log('Processing page source...')

    console.log('Doing some fancy stuff here ...')

    console.log('All done.')
    return Promise.resolve()
  })
}

(async function () {
  console.log('start')
  await x()
  console.log('end')
})()

最佳答案

是的,您应该等待 Page.loadEventFired Example

async function x () {
  const protocol = await CDP()

  const timeout = ms => new Promise(resolve => setTimeout(resolve, ms))

  // See API docs: https://chromedevtools.github.io/devtools-protocol/
  const { Page, Runtime, DOM } = protocol
  await Promise.all([Page.enable(), Runtime.enable(), DOM.enable()])

  await Page.navigate({ url: 'http://example.com' })

  // wait until the page says it's loaded...
  await Page.loadEventFired()

  console.log('Page loaded! Now waiting a few seconds for all the JS to load...')

  await timeout(3000) // give the JS some time to load

  protocol.close()

  console.log('Processing page source...')

  console.log('Doing some fancy stuff here ...')

  console.log('All done.')

}

顺便说一句,您可能还想用 try-finally 包装代码以始终关闭协议(protocol)。

 async function x () {
   let protocol

   try {
     protocol = await CDP()
     ...

   } finally {
     if(protocol) protocol.close()
   }

关于node.js - Chrome 远程接口(interface)的异步/等待问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45587917/

相关文章:

mysql - 在事务中插入多行,如果其中一行失败,则插入其余行

javascript - Javascript 异步函数和 Web worker 之间的区别?

c# - 试图理解 C# 中的异步/等待

node.js - Laravel Elixir 的关键 CSS

node.js - Elifecycle 错误是什么意思?

node.js - 在 NodeJS REPL 中,如何打印到标准输出?

node.js - http-proxy 模块错误 : Must provide a proper URL as target

c# - 如何在 C# Async/Await 应用程序中创建循环服务?

asynchronous - 如何等待rust中的异步函数调用列表?

async-await - 将 next.js 配置为使用 Babel 不转换异步函数