从Promise对象的实例内执行的setTimeout函数捕获异常 [英] Catching an exception from the setTimeout function executed inside an instance of a Promise object
本文介绍了从Promise对象的实例内执行的setTimeout函数捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的参与者,请告诉我解决方法.
Dear participants please tell me the solution.
在此代码块中,catсh方法完美地捕获了异常:
In this block of code, the catсh method perfectly catches the exception:
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方法:
And in this block, the catсh method will not be called:
с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`));
请说明:
- 为什么会发生这种情况(我想这是由于事件循环引起的)?
- 如何重写代码,以便在catch方法中捕获异常与setTimeout一起工作?
谢谢大家的回答!
这是一个生活例子:
import moment from "moment";
const Delay = (timeout, timePress) => {
return new Promise((res => setTimeout(() => {
res(`${moment().format("LTS")} ${timeout} ${timePress}`);
}, timeout * 1000)
));
};
export default Delay;
我想要,如果由于某种原因在setTimeout函数中引发了异常,我应该能够捕获它.像这样:
I want, If for some reason an exception is thrown in the setTimeout function, I should be able to catch it. Like this:
Delay.catch(() => console.log(`This code will not be executed`));
推荐答案
经过一些讨论和评论,我的任务通过这种方法得以解决:
After some discussions and comments, my task was solved by this approach:
const someFunction = timeout => new Promise(resolve => setTimeout(resolve, timeout));
someFunction(timeout).then(() => doSomething()).catch(() => console.log(`This code will not be executed`));
如果异步函数中发生异常:
If an exception occurs in an asynchronous function:
someFunction(timeout).then(ErrorEvent).catch(() => console.log(`This code will not be executed`));
这样的解决方案仍然可行:
Such solutions are still possible:
const testF = () => { throw new Error(`Упс! Бросили исключение.`) }
const genPromise = () => new Promise((resolve, reject) => {
setTimeout(() => {
try {
const res = testF()
resolve(res)
} catch (e) { reject(e) }
}, 1e3)
})
t1: {
const log = console.log.bind(console, 't1:')
const _then = log.bind(console, 'then:')
const _catch = log.bind(console, 'catch:')
genPromise()
.then(_then)
.catch(_catch)
.then(_then)
}
t2: {
const log = console.log.bind(console, 't2:')
const _then = log.bind(console, 'then:')
const _catch = log.bind(console, 'catch:')
void async function () {
let pRes = null
try {
pRes = await genPromise()
} catch (e) {
_catch(e.message)
}
_then(pRes)
}()
}
这篇关于从Promise对象的实例内执行的setTimeout函数捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文