Javascript 我如何打破承诺链?
在这种情况下,我应该如何停止承诺链? 仅当第一个then中的条件为真时,才执行第二个then的代码Javascript 我如何打破承诺链?,javascript,Javascript,在这种情况下,我应该如何停止承诺链? 仅当第一个then中的条件为真时,才执行第二个then的代码 var p = new Promise((resolve, reject) => { setTimeout(function() { resolve(1) }, 0); }); p .then((res) => { if(true) { return res + 2 } else { // do some
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)
})
只需使用类似于:reject('rejected') 在第一个任务的其他部分
P
.then((res) => {
if(true) {
return res + 2
} else {
reject('rejected due to logic failure' }
})
.then((res) => {
// executed only when the condition is true
console.log(res)
})
或者,您也可以使用.catch()将catch部分添加到您的第一个任务中
希望这有帮助。您可以在
else
块中抛出错误
,然后在承诺链的末尾捕获它:
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);
})
演示-你可以阅读,上面写着
Promise。然后
如果输入函数抛出错误或输入函数返回被拒绝的承诺,则返回被拒绝的承诺
如果您愿意,您可以阅读关于然后
一节中的,其中承诺2
指的是最终承诺:
如果oncompleted
或onRejected
引发异常e
,promise2
必须以e为理由拒绝。)
如果您愿意,您可以阅读精彩的:
then()
返回一个新的承诺Q(通过接收方的构造函数创建):
如果任何一个反应返回一个值,Q将用它来解析。
如果任何一个反应抛出一个异常,Q将被拒绝
你可以读到精彩的:
then(..)调用的实现或拒绝处理程序中引发的异常会导致下一个(链接的)承诺立即被该异常拒绝
可以将链移动到条件分支中:
p.then((res) => {
if(true) {
return Promise.resolve(res + 2).then((res) => {
// executed only when the condition is true
});
} else {
// do something
// chain ends here
}
});
在这里抛出一个错误对您的用例有效吗?如果你抛出任何类型的错误(即使只是抛出新错误();
可能会起作用),那么你就不会进入下一个错误。是的,我知道,但它会打破承诺链,因此不会击中下一个错误。如果这就是他想要做的,那么这将起作用reject
将不会在这里定义,因为它仅在新的承诺上下文中可用。这将不起作用,并且将它拉到范围外的变量中似乎非常不符合承诺。不仅没有定义,解决方案也是错误的。调用其中一个后,对resolve
或reject
(针对同一承诺)的其他调用将被忽略。是否有其他方法停止?因为else块中的代码不应该是“错误”@vincentf yes,返回Promise.reject('some message or not')在JS中,您可以抛出任何值,而不仅仅是错误<代码>抛出值
。承诺中的返回承诺。拒绝(值)
和抛出值
之间没有区别。