javascript - 如何使用 setTimeout 处理/捕获错误?
问题描述
function abc() {
try {
setTimeout(() => {
console.log('inside timeout!!');
throw new Error('Somehting went wrong!!');
}, 1000);
} catch (err) {
console.log('Gonna catch it here and throw is again', err);
throw new Error(err);
}
}
try {
abc();
} catch (err) {
console.log('err caught here', err);
}
如何捕捉错误?我应该在哪里用 try/catch 包装我的代码?即使承诺为什么 catch 块没有捕获错误。
async function abc() {
setTimeout(() => {
throw new Error();
}, 1000);
}
try {
abc();
} catch (err) {
console.log('err is ', err);
}
解决方案
将其包装成一个Promise:
function abc(simulateError) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (simulateError)
reject('Something went wrong')
else
resolve('foo')
})
})
}
// Call it using then/catch to handle result or errors...
abc(true).then(result => {
console.log(result)
})
.catch(err => {
console.log(err)
})
// or await on the Promise, which allows using try/catch.
;(async () => {
try {
const result = await abc(true)
console.log(result)
} catch (err) {
console.log(err)
}
})()
推荐阅读
- css - 如何允许在底部制作页脚但不让它覆盖内容
- php - 我可以根据类别在 WooCommerce 商店页面和产品中设置不同的排序吗
- java - 按第一列然后按第二列对二维数组进行排序
- mysql - 寻找一种更好的方法来使用 Laravel 处理大型 XML 文件以将部分导入 MySQL 数据库
- intel - 为什么我的服务器有 TEE 但不支持英特尔 SGX?
- python - 美丽的汤得到匹配的标签值之后的标签值
- android - 我不知道如何读取实时数据库并获取一些子数据来插入那些 Firestore 数据库
- python-3.x - 为什么我用python制作的这个游戏不能正常工作?
- python - 当记录具有特定状态时,如何使 Odoo 表单只读?
- git - 现在默认情况下 git set 'git pull' 和 rebase 吗?什么时候启动?