本文介绍了处理来自setTimeout的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于setTimeout中函数try-catch的简单问题

Simple question about try-catch for function in setTimeout

try {
    setTimeout(function () {
        throw new Error('error!');
    }, 300)
} catch (e) {
    console.log('eeee!')
    console.log(e)
}

为什么不使用catch-block?

Why dont work catch-block?

我能读到什么?

PS:关于处理此类错误的可能性的问题。不回答承诺

P.S: Question about possibility of handling errors like this. Dont answer about promises

推荐答案

计划运行 setTimeout 的函数被执行在主循环中,在发起它们的代码体外。

Functions scheduled to run with setTimeout are executed in the main loop, outside the body of code that originated them.

要处理错误,请输入 try-catch setTimeout 处理程序内:

To handle errors, put the try-catch inside the setTimeout handler:

setTimeout(function () {
  try {
    throw new Error('error!');
  } catch (e) {
    console.error(e);
  }
}, 300)

如果您需要访问错误调用 setTimeout 的块中的对象,使用:

If you need to access the Error object from block that called setTimeout, use Promises:

const promise = new Promise((resolve, reject) => {
  setTimeout(function () {
    try {
      throw new Error('error!');
    } catch (e) {
      reject(e)
    }
  }, 300)
})

promise
  .then(result => console.log("Ok " + result))
  .catch(error => console.error("Ouch " + error))

上面这个例子并不是使用 Promise 处理案例的最优雅方式。相反,实现一个延迟(ms)函数,如下所示:

This example above is not the most elegant way of handling the case with a Promise. Instead, implement a delay(ms) function like this:

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

然后调用

delay(300).then(myFunction).catch(handleError)

这篇关于处理来自setTimeout的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:48