asynchronous/等待Chrome远程界面的问题

我想testing这段代码,并等待直到它完成断言的结果。 不知道问题出在哪里,它应该在最后返回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 示例

 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来包装你的代码,以便总是closures协议。

  async function x () { let protocol try { protocol = await CDP() ... } finally { if(protocol) protocol.close() }