在解决“等待承诺”之前输入捕获块

时间:2019-03-22 21:31:05

标签: javascript promise async-await try-catch

尝试在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版本有什么不同?

3 个答案:

答案 0 :(得分:1)

我的最佳猜测是您的catch块没有<bean id="test" class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory"> <property name="host" value="${host}" /> <property name="privateKey"> <bean class="org.springframework.core.io.ByteArrayResource"> <constructor-arg value="#{'${my.sftp.private.key}'.bytes}"/> </bean> </property> <property name="port" value="${port}" /> <property name="user" value="${username}" /> <property name="allowUnknownKeys" value="true" /> </bean> 语句。因此,即使发生错误并被捕获,它所做的只是记录“快照失败”,然后继续运行该功能。试试

return

关于为什么会出现错误,请尝试记录实际错误以获取更深入的了解

答案 1 :(得分:1)

您似乎不太了解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块中进行处理,或在return块中的catch中进行处理。

Here is some documentation on try/catch(/finally)

答案 2 :(得分:0)

catch不是要检测错误,而是要处理错误。之后执行将继续正常进行。您应该分别在try { ... }或最后.then(...)内记录“快照捕获成功”。

  

为什么程序[进入]完全进入catch块?

引起错误。如果您将error登录到控制台,就会知道它是什么。

相关问题