首页 > 解决方案 > JavaScript:然后从获取中中断

问题描述

我正在寻找一种从 fetch-then-block 中打破的可能性。特别是:我想测试一个条件,如果它是真的,下一个'then'不应该被执行。那可能吗?

fetch(url).then(response => {
    return response.text();
}).then(text => {
    if (condition) {
        break
    }
}).then(...)

标签: javascript

解决方案


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
       }
   });

推荐阅读