【发布时间】:2019-08-13 22:31:33
【问题描述】:
尝试在 chrome 中保存相机快照。我有使用 Promise.resolve().then().catch() 方法的工作代码,我想转换为 async/await。
原码:
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 版本有什么不同?
【问题讨论】:
标签: javascript promise async-await try-catch