最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Try catch block is not catching nested callbacks - Stack Overflow

programmeradmin3浏览0评论

I'm trying to understand how to use try/catch when it es to nested callbacks. Why doesn't this piece of code catch my new error ?

function test(cb) {
  setTimeout(function() {
    throw new Error("timeout Error");
  }, 2000);
}

try {
  test(function(e) {
    console.log(e);
  });
} catch (e) {
  console.log(e);
}

I'm trying to understand how to use try/catch when it es to nested callbacks. Why doesn't this piece of code catch my new error ?

function test(cb) {
  setTimeout(function() {
    throw new Error("timeout Error");
  }, 2000);
}

try {
  test(function(e) {
    console.log(e);
  });
} catch (e) {
  console.log(e);
}

Share Improve this question edited Oct 21, 2016 at 14:16 user3589620 asked Oct 21, 2016 at 14:05 runners3431runners3431 1,4551 gold badge13 silver badges31 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

The error happens asynchronously, when the function passed to setTimeout runs. By the time the error is thrown, the test function has already finished executing.

There are many ways to set a timer for Javascript execution. Here's one way that uses Promise.race():

(async () => {
  try {
    await Promise.race([

      // Timer.
      new Promise((res, rej) => {
        setTimeout(() => {
          rej("Timeout error!");
        }, 2000);
      }),

      // Code being timed.
      new Promise((res, rej) => {
        // Do some stuff here.
        // If it takes longer than 2 seconds it will fail.
        res("Finished in under 2 seconds.");
      })

    ]);
  } catch (err) {
    console.log("we got an err: " + err);
  }
})();
发布评论

评论列表(0)

  1. 暂无评论