[英]Nodejs. Unhandled Promise Rejection
我正在嘗試測試某些功能。 在routes.js文件中,我放置了以下代碼:
async function getPic(arg) {
const browser = await puppeteer.launch(/*{headless: false}*/);
const page = await browser.newPage();
await page.goto(arg);
await page.setViewport({width: 1000, height: 500})
await page.screenshot({path: 'pic.png'});
await broswer.close();
}
我閱讀了有關異步/等待的內容(這是我第一次使用它)。 雖然我收到錯誤消息,但代碼無法正常工作:
(node:5896) UnhandledPromiseRejectionWarning: Error: Navigation Timeout Exceeded
: 30000ms exceeded
at Promise.then (C:\...\node_modules\puppeteer\lib\NavigatorWatcher.js:73:21
)
at <anonymous>
(node:5896) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function without a catch
block, or by rejecting a promise which was not handled with .catch(). (rejection
id: 1)
(node:5896) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
不幸的是,我不知道這意味着什么。 我在這里在stackoverflow上發現了類似的問題: NodeJS未處理的承諾拒絕
但是,不幸的是,我對如何解決此錯誤並不清楚。
當我在獨立節點環境中測試此代碼段時-就像我在項目中所做的那樣,僅意味着此代碼沒有其他任何內容,那么它以某種方式起作用。
當我將此函數放在我的routes.js文件中,然后在發生后事件時調用該函數時,我得到了錯誤。
這是調用此函數的代碼:
app.post('/sc', function(req, res){
var url = req.body.convo
console.log(url)
getPic(url);
})
您需要await getPic(url);
。
另外,您在瀏覽器中使用了拼寫錯誤的瀏覽器await broswer.close();
您應該在調用異步函數之前使用await,並將await調用包裝到try catch結構中。
app.post('/sc', async (req, res) => {
const url = req.body.convo
try {
var picture = await getPic(url);
//some logic or render response
} catch (error){
//here you should handle error
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.