javascript - 拦截 fetch() 请求,将其搁置并在满足特定条件时恢复

标签 javascript fetch

以下代码在检测到对某个端点的 fetch() 请求时会触发警报。这样做会使请求停止继续,等待用户关闭警报,然后让请求流向端点。

我的问题是如何实现相同的中断,而不是等待警报关闭,我需要等待 cookie 出现的请求。我觉得需要用 Promises 来完成 :)

const x = window.fetch;
window.fetch = function() {
   if (arguments[0] == '/certain_endpoint') { alert('stopping for a while'); }
   return x.apply(this, arguments)
}

最佳答案

您可以使用 setInterval 并 promise 定期轮询特定条件并在满足时解决。

const x = window.fetch;
window.fetch = function() {
  if (arguments[0] == '/needs_cookie') {
    return waitForCookie().then(cookie => {
      return x.apply(this, arguments);
    });
  } else {
    return x.apply(this, arguments);
  }
}

// Returns a promise that resolves to a cookie when it is set.
function waitForCookie() {
  return new Promise(function (resolve, reject) {
    var intervalID = setInterval(checkForCookie, 100);
    function checkForCookie() {
      var cookie = getCookie();
      if (cookie) {
        clearInterval(intervalID);
        resolve(cookie);
      }
    }
  });
}

// Here, getCookie() returns undefined the first two times it's called.
// In reality, it should just parse document.cookie however you normally do.
var attempts = 0;
function getCookie() {
  if (attempts < 2) {
    attempts++;
    console.log('Attempts: ', attempts);
    return undefined;
  } else {
    return 'cookie!';
  }
}

如果您正在尝试做更复杂的异步操作,包括轮询,您可能需要查看 RxJS .

关于javascript - 拦截 fetch() 请求,将其搁置并在满足特定条件时恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816353/

相关文章:

javascript - 飞行前停止从 Firefox 到 Beego 服务器的 CORS 提取

php - 如何使用mysql_fetch_array 的结果?

node.js - 如果我禁用 NODE_TLS_REJECT_UNAUTHORIZED,我的请求仍然被拒绝

javascript - 使用 Reactjs 获取 GET 请求 - 如何在请求中实现可重用组件来呈现数据?

javascript - 即使验证正则表达式错误也提交表单

javascript - 在 JQuery 中选择特定的子元素?

javascript - Font Awesome 5 伪元素与 Webpack

javascript - 如何使字段显示为文本而无需 ng-repeat 内的 HTML 代码

php - 如何检测按下了哪个提交按钮?

javascript - 是否有类似于 fetch() API 中的 readyState 的东西?