Patrick
Patrick

Reputation: 8063

async/await issues with Chrome remote interface

I'd like to test this piece of code and wait until it's done to assert the results. Not sure where the issue is, it should return the Promise.resolve() at the end, but logs end before the code is executed.

Should Page.loadEventFired also be preceded by 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')
})()

Upvotes: 2

Views: 1271

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Yes you should await for 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.')

}

BTW you might also want to wrap your code with try-finally to always close protocol.

 async function x () {
   let protocol

   try {
     protocol = await CDP()
     ...

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

Upvotes: 2

Related Questions