从在Promise对象的实例内部执行的setTimeout函数中捕获异常

问题描述 投票:1回答:1

亲爱的参与者,请告诉我解决方案。

在此代码块中,catсh方法完美地捕获了异常:

const myPromise = new Promise(() => {
  throw new Error(`Oops! Threw an exception`);
});

// We catch the exception in the method `catch`.
myPromise
  .catch((error) => console.log(error.message));

并且在此块中,不会调用catсh方法:

сonst TIMEOUT = 1000;

const mySecondPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    throw new Error(`Error in asynchronous function`);
  },
  TIMEOUT
  );
});

mySecondPromise
  .catch(() => console.log(`This code will not be executed`));

请说明:

  1. 为什么会这样(我想这是由于事件循环造成的?)>
  2. 如何重写代码,以便在catch方法中捕获异常与setTimeout一起使用?
  3. 谢谢大家的回答!

尊敬的与会者,请告诉我解决方案。在此代码块中,catсh方法完美地捕获了以下异常:const myPromise = new Promise(()=> {throw new Error(`Oops!Throw a ...

javascript promise settimeout
1个回答
2
投票
超时代码在promise上下文之外执行。您要执行的操作是调用“拒绝”并显示错误:
© www.soinside.com 2019 - 2024. All rights reserved.