admin管理员组文章数量:1320821
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
2 Answers
Reset to default 10The 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);
}
})();
本文标签: javascriptTry catch block is not catching nested callbacksStack Overflow
版权声明:本文标题:javascript - Try catch block is not catching nested callbacks - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742089407a2420173.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论