我一直在尝试Promise和错误处理,但是我无法解释一段代码的行为。 Promise.reject被调用了两次,第一个被完美地处理,但后者根本没有被嘲笑。
const a = Promise.resolve('test');
a
.then(item => Promise.reject('promise reject 1'))
.then(
(a) => {
console.log(a); // value: test
},
(err) => {
console.log(err); // value: promise reject 1
}
).then((a) => {
console.log('continue1'); // being called
Promise.reject('promise reject 2') // called but not caught
},
(err) => {
console.log(err); // never being called
})
.catch((err) => {
console.log(err); // never being called
});
我希望catch能够捕获第14行(Promise.reject('promise reject 2')
)中引入的错误,但是从来没有调用catch处理程序
答案 0 :(得分:1)
Promise.reject()
仅使一个被拒绝的Promise对象。您的连锁店对此一无所知,除非您将其退回。如果返回,则下一个catch
将捕获它:
const a = Promise.resolve('test');
a
.then(item => Promise.reject('promise reject 1'))
.then(
(a) => {
console.log(a); // value: test
},
(err) => {
console.log(err); // value: promise reject 1
}
).then((a) => {
console.log('continue1'); // being called
return Promise.reject('promise reject 2') // << ---- Return me!
},
(err) => {
console.log(err); // never being called
})
.catch((err) => {
console.log("from catch:",err); // caught!
})
您也可以在throw
中then()
:
const a = Promise.resolve('test');
a
.then(item => Promise.reject('promise reject 1'))
.then(
a => {
console.log(a); // value: test
},
err => {
console.log(err); // value: promise reject 1
})
.then(
a => {
console.log('continue1'); // being called
throw(new Error('promise reject 2')) // <-- no return required
},
err => {
console.log(err); // never being called
})
.catch(err => {
console.log("from catch:",err.message); // caught!
})