我不太理解在嵌套的Promise中,将.catch
放置在then
之前和之后的区别。
方案1:
test1Async(10).then((res) => {
return test2Async(22)
.then((res) => {
return test3Async(100);
}).catch((err) => {
throw "ERROR AFTER THEN";
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
备选方案2:
test1Async(10).then((res) => {
return test2Async(22)
.catch((err) => {
throw "ERROR BEFORE THEN";
})
.then((res) => {
return test3Async(100);
});
}).then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
每个函数的行为如下,如果数字是<0
则test1失败,如果数字是> 10
则test2失败,如果数字不是100
则test3失败。 在这种情况下,只有test2失败。我尝试运行并使test2Async失败,无论是之前还是之后都会以相同的方式执行,并且不执行test3Async。 有人能解释一下在不同位置放置catch的主要区别吗?
在每个函数中,我使用
console.log('Running test X')
来检查它是否被执行。这个问题是因为我之前发布的线程引起的如何将嵌套回调转换为Promise?。 我认为这是一个不同的问题,值得发表另一个主题。