我是JavaScript的新手,正在尝试编写一个脚本,该脚本将使用Axios将多个HTTP请求发送到Web服务器。服务器的设计方式是它将随机发送对请求的响应。现在,我希望脚本在收到一个响应后就停止发送请求。我还可以编写的基本代码是:
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;
}
}
假设此.js文件将出现在客户端的浏览器中。
答案 0 :(得分:0)
编辑:基于this comment,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