[英]How can I send multiple HTTP requests to a URL using Axios and stop sending once I receive a response from one of the request?
我是 javascript 的新手,并尝试编写一个脚本,该脚本将使用 ZD3E28535C74CCEE23888 向 web 服务器发送多个 HTTP 请求。 服务器的设计方式是它会随机发送响应到请求。 现在,我希望脚本在收到一个响应后停止发送请求。 我可以编写的基本代码是:
while (1) {
axios.get('http://localhost:8080/ubuntu_default.html', { withCredentials: true }).then(function (response) {
document.body.innerHTML = generateSuccessHTMLOutput(response);
break;
});
function generateSuccessHTMLOutput(response) {
return response.data;
}
}
假设 this.js 文件将出现在客户端的浏览器中。
编辑:基于此评论op 只想轮询一个端点并在他得到响应后停止。
示例代码:
(async() {
let r = await poll('http://localhost:8080/ubuntu_default.html');
console.log(r);
})();
async function poll(endpoint) {
let countOfError = 0;
const maxErrors = 10;
let resp = null;
while (true) {
try {
resp = await axios.get(endpoint, { withCredentials: true }));
//check if resp is "success" then break;
//What does a successful response look like?
if (resp.data.success) break;
} catch (e) {
//console.error(e); optional
countOfErrors += 1;
if (countOfErrors > maxErrors) break;
}
}
return resp;
}
您可以使用类似Promise.race
let promises = [];
for (let i = 0; i<10; i++)
promises.push(
axios.get('http://localhost:8080/ubuntu_default.html',
{ withCredentials: true }));
Promise.race(promises).then( generateSuccessHTMLOutput );
//Called with whichever promise fulfills first
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.