拦截fetch()请求,将其置于保持状态并在满足某些条件时恢复

时间:2017-12-14 14:59:07

标签: 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)
}

2 个答案:

答案 0 :(得分:1)

您可以将setInterval与承诺一起使用,定期轮询某个条件,并在符合条件时解决。

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

答案 1 :(得分:0)

index

您可以返回一个承诺,而不是在一段时间后解决