![](/img/trans.png)
[英]Can you use await in promise' catch block of javascript?
[英]Catch block is entered before “await Promise” is resolved
嘗試將相機快照保存在Chrome中。 我有使用Promise.resolve()。then()。catch()方法的工作代碼,我想轉換為異步/等待。
原始代碼:
function onSnapshotButtonClick() {
imageCapture.takePhoto()
.then(blob => createImageBitmap(blob))
.then(imageBitmap => {
drawCanvas(imageBitmap);
})
.catch(error => console.error("Snapshot failed."));
console.log("Snapshot capture successful.");
})
新代碼:
var blob;
async function onSnapshotButtonClick() {
// Take snapshot
try {
blob = await imageCapture.takePhoto();
let imageBitmap = createImageBitmap(blob);
drawCanvas(imageBitmap);
} catch (error) {
console.error("Snapshot failed.");
}
console.log("Snapshot successful.")
// Do other stuff with blob...
})
但是當運行上面的代碼時,我都收到了“快照失敗”的信息。 和“快照成功”。 打印到控制台,什么也不會繪制到畫布(稍后定義一個功能)。 為何程序進入catch塊,而不是在退出函數時退出函數?
編輯:謝謝,我現在知道catch塊應該包含return語句,並且可以通過打印error.message來了解有關該錯誤的更多信息。 似乎imageBitmap不是有效的格式,這在async / await版本中引起了問題。 問題仍然存在,因為原始版本沒有此問題,導致行為更改的async / await版本有什么不同?
我最好的猜測是您的catch塊沒有return
語句。 因此,即使發生錯誤並被捕獲,它所做的只是記錄“快照失敗”,然后繼續運行該功能。 嘗試
try{
...
} catch(err){
console.log("Snapshot failed: " + err)
return;
}
//then do whatever it is you need if snapshot successful
至於為什么有錯誤,請嘗試記錄實際的錯誤,以便更好地了解
看來您不太了解try/catch(/finally)
塊的工作原理。
基本上,您編寫的代碼是(用偽代碼):
Try this block :
blob = await imageCapture.takePhoto();
let imageBitmap = createImageBitmap(blob);
drawCanvas(imageBitmap);
If any lines of the block above fails, then do this :
console.error("Snapshot failed.");
After one of the 2 code blocks above are done, keep going
console.log("Snapshot successful.")
因此,您的try
塊有一個例外,進入catch
塊,然后繼續進行。
如果要對圖像進行某些處理,請在try
塊中進行處理,或在catch
塊中return
。
catch
並不是要檢測錯誤,而是要處理錯誤。 之后執行將繼續正常進行。 您應該分別在try { ... }
或最后一個.then(...)
內記錄“快照捕獲成功。
程序為什么[全部]進入catch塊?
導致發生錯誤。 如果將error
記錄到控制台,您將找出error
所在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.