Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Handle error from setTimeout

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)
}

Why dont work catch-block?

What I can read about this?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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!');
      resolve(); // if the previous line didn't always throw

    } catch (e) {
      reject(e)
    }
  }, 300)
})

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

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))
}

Then call

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...