2017-08-09 62 views
2

我想測試這段代碼,並等待它完成斷言結果。不知道問題出在哪裏,它應該在最後返回Promise.resolve(),但在執行代碼之前記錄end異步/等待Chrome遠程接口的問題

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

回答

2

是的,你應該指日可待Page.loadEventFiredExample

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() 
    } 
+0

很簡單,謝謝!將花費更多的嘗試來完全獲得異步/等待。 – Patrick