繁体   English   中英

如何从异步代码中捕获错误

[英]How to catch error from Asynchronous code

以下代码行能够捕获错误(因为它是同步的)

 new Promise(function(resolve, reject) {
        throw new Error("Whoops!");
    }).catch(alert);

但是,当我修改我的代码时,如下所示

 new Promise(function(resolve, reject) {
      setTimeout(() => {
        throw new Error("Whoops!");
      }, 1000);
    }).catch(alert);

它无法捕获错误。 我有一个用例,我想抓住这个错误。 我怎样才能实现它?

点击链接“ https://bytearcher.com/articles/why-asynchronous-exceptions-are-uncatchable/ ”,我就能理解为什么会这样。 只是想知道是否还有任何解决方案来捕获这样的错误。

请注意,通过使用setTimeout,我指的是异步调用的使用,它可以给出一些响应,或者在我在fetch语句中提供不正确的URL时会出现错误。

fetch('api.github.com/users1')   //'api.github.com/user'is correct url
.then(res => res.json())
.then(data => console.log(data))
.catch(alert);

你需要一个try / catch你问里面的功能setTimeout调用:

new Promise(function(resolve, reject) {
    setTimeout(() => {
        try {
            throw new Error("Whoops!"); // Some operation that may throw
        } catch (e) {
            reject(e);
        }
    }, 1000);
}).catch(alert);

函数setTimeout调用完全独立于promise执行器函数的执行上下文。

在上面我假设throw new Error("Whoops!")是可能抛出错误的操作的替身,而不是实际的throw语句。 但是,如果你真的在throw ,你可以直接调用reject

new Promise(function(resolve, reject) {
    setTimeout(() => {
        reject(new Error("Whoops!"));
    }, 1000);
}).catch(alert);

使用拒绝抛出错误,

new Promise(function(resolve, reject) {
  setTimeout(() => {
    reject(new Error("Whoops!"))
  }, 1000);
}).catch(alert);

要处理错误,请将try-catch放在setTimeout处理程序中:

 new Promise(function(resolve, reject) {
      setTimeout(() => {
          try{
                  throw new Error("Whoops!");
          }catch(alert){
                  console.log(alert);
          }
       }, 1000);
 });

你也可以用一点实用工具:

function timeout(delay){ 
  return new Promise(resolve => setTimeout(resolve, delay)); 
}

timeout(1000)
  .then(() => {
     throw new Error("Whoops!");
  })
  .catch(alert);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM