我正在使用一些通过XML进行通信的API服务器。
我需要发送,比如说:20个相同的POST请求。
我正在用Node JS编写。
容易
但是-因为我要加倍处理,并且我想避免服务器泛滥(并且被踢),所以如果(XML)响应包含特定文本(成功信号),则需要中断发送循环):<code>555</code>
,或者实际上只是“ 555”(文本用其他XML短语包装)。
我尝试根据成功信号中断循环,并尝试将其“导出”到循环外(认为在循环条件下解决该循环可能会很不错)。
猜想很容易,但是作为一个新手,我不得不打电话寻求帮助:) 附加相关代码(简体)。
非常感谢!
const fetch = require("node-fetch");
const url = "https://www.apitest12345.com/API/";
const headers = {
"LOGIN": "abcd",
"PASSWD": "12345"
}
const data = '<xml></xml>'
let i = 0;
do { // the loop
fetch(url, { method: 'POST', headers: headers, body: data})
.then((res) => {
return res.text()
})
.then((text) => {
console.log(text);
if(text.indexOf('555') > 0) { // if the response includes '555' it means SUCCESS, and we can stop the loop
~STOP!~ //help me stop the loop :)
}
});
i += 1;
} while (i < 20);
答案 0 :(得分:0)
在异步等待中使用简单的for循环。
const fetch = require("node-fetch");
const url = "https://www.apitest12345.com/API/";
const headers = {
"LOGIN": "abcd",
"PASSWD": "12345"
}
const data = '<xml></xml>'
for (let i = 0; i < 20; i++) {
const res = await fetch(url, { method: 'POST', headers: headers, body: data});
if (res.text().indexOf('555') !== -1)
break;
}