try catch的两种用法:
1、避免代码发生错误进行阻塞,如果不写如下代码,js就会报错,阻塞往下进行
try {
throw new TypeError('类型错误')
} catch (error) {
console.log(error) // TypeError: 类型错误
}
2、try cath 还可以对promise的reject状态进行处理
promise的catch是可以对错误进行处理的
Promise.reject('出错了')
.catch(e => {
console.log(e === '出错了')
})
// true
try catch也可以对promise的reject状态进行一个处理
async function f4() {
try {
const z = await Promise.reject(30);
} catch (e) {
console.error(e); // 30
}
}
f4();
async function f4() {
try {
const z = await Promise.reject(300000)
console.log('z',z) // 没有任何的打印,直接就没走赋值
} catch (e) {
console.log(e) // 300000
}
}
f4()
async function f4() {
try {
await Promise.reject(300000) // await 语法没必要非得将结果赋予一个值
} catch (e) {
console.log(e)
}
}
f4()
处理被拒绝的 promise
你可以链式调用 catch()(而不是使用 try)以在等待 promise 兑现之前处理被拒绝的 promise。
const response = await promisedFunction().catch((err) => {
console.error(err);
return "default response";
});
// response will be "default response" if the promise is rejected
(async() => {
const response = await Promise.reject(30).catch((err) => {
console.log(err) // 30
return 'default response'})
console.log(response) // default response
})()