首页 > 解决方案 > 如何停止脚本在 .then 阶段执行?

问题描述

如何停止脚本在 .then 阶段执行?如果 response 和 response.text 不为空,我希望脚本停止执行

fetch(url, {
  method: 'POST',
  body: data,
  credentials: 'include',
  })
  .then(response => response.text())
  .then(html => {
    if (html && html.length) {
      $('#modal-content').html('');
      $('#modal-content').append(html);
     //STOP here.
    }
  })
  .then(({ status }) => {
    if (status === 200) {
      document.location.reload(true);
    } 
  })

UPD:我最终写了另一个 if 条件

  if (status === 200 && $('#notavailable-modal').length == 0) {
      document.location.reload(true);
    }

标签: javascriptfetch

解决方案


 throw "Stop!";

您可以拒绝返回的承诺,然后.then不会执行进一步的处理程序。

或者您只是将两个.thens 合并为一个:

if (html && html.length) {
  $('#modal-content').html('');
  $('#modal-content').append(html);
  // no need to STOP here
} else if (status === 200) {
  document.location.reload(true);
} 

推荐阅读