<分区>
我正在寻找打破先获取后阻塞的可能性。特别是:我想测试一个条件,如果条件为真,则不应执行下一个“then”。这可能吗?
fetch(url).then(response => {
return response.text();
}).then(text => {
if (condition) {
break
}
}).then(...)
标签 javascript
<分区>
我正在寻找打破先获取后阻塞的可能性。特别是:我想测试一个条件,如果条件为真,则不应执行下一个“then”。这可能吗?
fetch(url).then(response => {
return response.text();
}).then(text => {
if (condition) {
break
}
}).then(...)
最佳答案
您可以从 then()
方法的回调函数中抛出错误。
抛出错误会拒绝then()
方法返回的Promise
,并会引起catch()
方法的回调函数执行而不是下一个 then()
方法。
fetch(url)
.then(response => response.text())
.then(text => {
if (condition) {
throw new Error('promise chain cancelled');
}
})
.then(...)
.catch(error => console.log(error));
理想情况下,您应该使用一些自定义名称或错误代码抛出错误,您可以在 catch
block 中使用这些代码来检测错误是否因条件为真而抛出。
fetch(url)
.then(response => response.text())
.then(text => {
if (condition) {
const error = new Error('promise chain cancelled');
error.name = 'CancelPromiseChainError';
throw error;
}
})
.then(...)
.catch(error => {
if (error?.name == 'CancelPromiseChainError') {
// code to run when promise chain is cancelled
}
});
关于JavaScript:然后从获取中中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62982489/