async /等待Chrome远程界面问题

时间:2017-08-09 10:20:36

标签: 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')
})()

1 个答案:

答案 0 :(得分:2)

是的,您应该等待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包装代码以始终关闭协议。

 async function x () {
   let protocol

   try {
     protocol = await CDP()
     ...

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