首页 > 解决方案 > 终止 javascript 执行

问题描述

我可以找到一种方法来从我的第一次提取中终止我的 javascript 执行:

document.querySelector('#elsubmit').onclick = (event) => {

      fetch('/', {

        method: 'POST',
        body: JSON.stringify({
          nombrelink: nombrelink
        }),
        headers: {
          "Content-type": "application/json; charset=UTF-8",
          "X-CSRFToken": getCookie('csrftoken'),
          "Accept": "application/json"
        }
        })
        .then(response => response.json())
        .then(result => {
          

        if (result['nadie']) {
  

        }
        else {
          document.getElementById('spanthelinkbox').style.borderColor = 'red';
          document.getElementById('spanthelink').style.display = 'block';
          document.getElementById('spanthelink').innerHTML = 'Link ya tomado';
          event.preventDefault();
          return;
          return;
          return false
          return false
          return false

        }

    });

  
  fetch(`https://www.url.com/${urlname}`, {
    method: 'POST',
    body: formData,
  
    headers: {
      "X-CSRFToken": getCookie('csrftoken')
    }
  })
  .then(response => response.json())
  .then(result => {
      window.location = "https://www.url.com/" + result['urlname'].toLowerCase() 
  })
  
  }

代码到达所有写入的地方,return false但它无法阻止下一次提取运行。我想停止执行最后一次提取,但使用 return false,event.preventDefault();return;似乎不起作用。就像无法停止父事件一样。

有任何想法吗?

标签: javascript

解决方案


Fetch 返回一个 Promise,你可以链接多个 Promise,并在第二个请求中使用第一个请求的结果,以此类推。

    var result =('/', {
    method: 'POST',
    body: JSON.stringify({
      nombrelink: nombrelink
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8",
      "X-CSRFToken": getCookie('csrftoken'),
      "Accept": "application/json"
    }
    }).then(response => response.json())
    .then(result => {
    if (result['nadie']) {
   return (`https://www.url.com/${urlname}`, {
   method: 'POST',
   body: formData,
   headers: {"X-CSRFToken": getCookie('csrftoken')}
    })}
    else {
      document.getElementById('spanthelinkbox').style.borderColor = 'red';
      document.getElementById('spanthelink').style.display = 'block';
      document.getElementById('spanthelink').innerHTML = 'Link ya tomado';
      event.preventDefault(); 
     return false;
    }

});

// I'm using the result variable to show that you can continue to extend the chain from the returned promise
result.then(function(r) {
  console.log(r); // 2nd request result
});

推荐阅读