【问题标题】:Catch block is entered before "await Promise" is resolved在“await Promise”解决之前进入 Catch 块
【发布时间】: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


    【解决方案1】:

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

    为什么程序会进入 catch 块 [at all] ?

    导致发生错误。如果您将 error 记录到控制台,您会发现它是什么。

    【讨论】:

      【解决方案2】:

      我最好的猜测是你的 catch 块没有 return 语句。因此,即使出现错误并被捕获,它所做的只是记录您的“快照失败”,并继续运行该功能。试试

      try{
        ...
      } catch(err){
          console.log("Snapshot failed: " + err)
          return;
      }
      //then do whatever it is you need if snapshot successful
      

      至于为什么会出现错误,请尝试记录实际错误以获得更好的洞察力

      【讨论】:

      • 感谢您的洞察力。结果发现错误正在发生,因为 drawCanvas() 抱怨 imageBitmap 的类型。那么我的问题是,既然原始代码能够绘制图像,那么导致这种情况的 async/await 版本有什么问题?
      • 所以我不确定 drawCanvas()、createImageBitmap() 或 image.takePhoto() 函数是如何工作的,但我猜这是因为 createImageBitmap() 也可能是异步的?尝试在它前面添加另一个await,如let imageBitmap = await createImageBitmap(blob);,也许看看会发生什么?
      【解决方案3】:

      您似乎并不真正了解 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

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

      【讨论】:

        猜你喜欢
        • 2020-02-19
        • 1970-01-01
        • 2020-12-02
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 2020-12-27
        • 1970-01-01
        • 2017-07-27
        相关资源
        最近更新 更多