我正在从事JavaScript项目,我们在其中调用一些肥皂API接收数据,然后在前端显示此数据。托管后端的服务器有时会降低,从而导致API调用的故障。我想排队在前端的所有API呼叫,这些呼叫在服务器下降时会失败,并保持轮询服务器直到返回在线,然后开始从队列中排出API请求,以从前端处理它们。有人可以通过解释可以在JavaScript中实现这一点来帮助我吗?
我正在使用简单的JavaScript HTTP请求来调用API。目前,我们要做的是,如果API失败,我们会继续一次又一次地打电话,直到它给出响应。这种方法的问题是,如果存在多个不同的API故障,则仅在跟踪中进行了最后一次故障。我想跟踪所有失败的API呼叫,并在服务器返回在线后按顺序拨打它们。如果可以在不使用外部库的情况下可以完成。
当前代码:
API调用:
function sendXmlRequest(payload) {
// Build http request
var http = new XMLHttpRequest();
http.open('POST', endpoint, true);
http.timeout = 30000;
http.setRequestHeader('Content-type', 'text/xml');
http.onreadystatechange = function() {
if (http.readyState === 4 && http.responseXML) {
if (http.status === 200) {
setResponsePayload(http.responseXML.documentElement);
} else if (http.status === 500) {
setErrorResponsePayload(http.responseXML.documentElement);
}
}
};
http.onerror = function() {
setErrorResponse();
}
http.ontimeout = function() {
setErrorResponse();
}
// Send request
http.send(payload);
}
重试:
function retryConnection() {
setTimeout(function() {
sendXmlRequest(payload);
}, 2000);
}
您可以做以下操作:
var fetch = {
queue: [],
request : function (url, method) {
// Create the XHR request
var request = new XMLHttpRequest();
var self = this;
// Return it as a Promise
return new Promise(function (resolve, reject) {
// Setup our listener to process compeleted requests
request.onreadystatechange = function () {
// Only run if the request is complete
if (request.readyState !== 4) return;
// Process the response
if (request.status >= 200 && request.status < 300) {
// If successful
resolve(request);
} else {
self.queue.push({url, method});
// If failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
// Setup our HTTP request
request.open(method || 'GET', url, true);
// Send the request
request.send();
});
},
retry: function() {
var self = this;
this.queue.forEach(function(meta) {
console.log(meta);
self.request(meta.url, meta.method).then(
() => self.queue.filter(e => e.url !== meta.url && e.method !== meta.method)
);
});
}
};
setInterval(() => {
fetch.retry();
}, 10000);
// Success case.
fetch.request('https://api.github.com/emojis','GET')
.then(console.log, console.error);
//Error case.
fetch.request('https://api.github.com/eee','GET')
.then(console.log, console.error);
首先,我有3个部分的对象fetch
:
var fetch = {
queue: [], // on error, we add url and method on the queue.
request : function (url, method) {
// Perform request.
},
retry: function() {
// Retry what ever you have on queue. Remove when success.
}
};
然后,应要求,当出现错误时,我添加了在队列数组中重播请求所需的所有信息。
在另一侧,重试方法将在此队列上循环,并重播所有请求失败。
为了使代码尽可能简单,我在代码上引入了弱点。如果您想从后端操纵AJAX请求答案,如果此请求失败,请在尝试几次尝试后进入队列和成功。您实际上无法用它来重述API。
如果这种情况对您很重要,请让我知道,我将征收另一个(更复杂的(批准。