// 异步异常
new Promise((resolve, reject) => {
setTimeout(() => {
throw "err";
}, 0);
})
.then((value) => {
console.log(value);
})
.catch((reason) => {
console.log(reason);
});
// 控制台抛出错误
// 同步异常
new Promise((resolve, reject) => {
throw "err";
})
.then((value) => {
console.log(value);
})
.catch((reason) => {
console.log(reason);
});
// output: err
// 同步异常 Promise 的状态
const p = new Promise((resolve, reject) => {
throw "err";
})
// output: rejected
// 异步异常 Promise 的状态
const p = new Promise((resolve, reject) => {
setTimeout(() => {
throw "err";
});
})
// output: pending
问题 2:异步异常在 then/catch 回调里面.
// 异步异常
Promise.resolve().then(()=>{
setTimeout(()=>{
throw 'err'
},0)
}).catch((err)=>{
err
}).then((value)=>{
console.log(value)
})
// 输出:
// undefined
// x Uncaught err
// 同步异常
Promise.resolve().then(()=>{
throw 'err'
}).catch((err)=>{
console.log(err)
}).then((value)=>{
console.log(value)
})
// 输出:
// err
// undefined