以下代码在检测到对某个端点的 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/