node.js - 从服务器获取特定文本响应时停止循环
问题描述
我正在使用一些通过 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);
解决方案
使用带有异步等待的简单 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;
}
推荐阅读
- kql - 如何在 KQL 中将主机字节顺序 IP 地址转换为 ASCII IP xxxx
- html - 为什么设置填充使两个水平 div 垂直?
- javascript - 即使页面放大并重新加载后,窗口高度和文档高度也是相同的。垂直滚动条可见
- python - 根据 Pandas 中的两个第一列合并具有不同行数的列
- javascript - 创建触发器 VS 后端查询、性能和资源
- spartacus-storefront - 斯巴达克斯店面中的 PDP 页面和添加到购物车问题
- firebase - sendEmailVerification 与 sendSignInLinkToEmail 使用 firebase 进行电子邮件验证
- python - 了解 Python 中基于冲突的搜索 MAPF (cbs-mapf) 包
- python - 我希望 x 增加
- java - Spring控制器测试路径变量给出404