javascript - JavaScript:然后从获取中中断
问题描述
我正在寻找一种从 fetch-then-block 中打破的可能性。特别是:我想测试一个条件,如果它是真的,下一个'then'不应该被执行。那可能吗?
fetch(url).then(response => {
return response.text();
}).then(text => {
if (condition) {
break
}
}).then(...)
解决方案
then
你可以从块中抛出一个错误。抛出错误将拒绝Promise
当前then
块返回的内容,并导致该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
块中使用这些名称或错误代码来检测是否由于条件为真而引发了错误。
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
}
});
推荐阅读
- python - 从学术花括号格式中提取电子邮件地址
- android - Android:未解析的包,即使我修改了清单的属性`package`的值
- laravel - Laravel Eloquent(模型属性不会显示)
- r - 如何计算R中数据框中每个组的t检验
- java - JVM 内存增长超出 ECS 容器的限制
- java - 如何读取 jar 中的文件?
- python - Python regex:如何在字符串中只增加一个数字?
- python - Django URL 重定向问题
- c++ - C++:basic_string::_M_construct null 对 Graph BFS 算法无效错误
- sql - 在 SELECT 的结果中将空/NULL 结果替换为“FALSE”