在这种情况下我应该如何停止 promise 链? 只有当第一个 then 中的条件为真时,才执行第二个 then 的代码。
var p = new Promise((resolve, reject) => {
setTimeout(function() {
resolve(1)
}, 0);
});
p
.then((res) => {
if(true) {
return res + 2
} else {
// do something and break the chain here ???
}
})
.then((res) => {
// executed only when the condition is true
console.log(res)
})
最佳答案
您可以在 else
block 中抛出
一个Error
,然后在 promise 的末尾catch
链:
var p = new Promise((resolve, reject) => {
setTimeout(function() {
resolve(1)
}, 0);
});
p
.then((res) => {
if(false) {
return res + 2
} else {
// do something and break the chain here ???
throw new Error('error');
}
})
.then((res) => {
// executed only when the condition is true
console.log(res)
})
.catch(error => {
console.log(error.message);
})
关于javascript - 如何打破 promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772154/