首页 > 解决方案 > 从服务器获取特定文本响应时停止循环

问题描述

我正在使用一些通过 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);

标签: node.js

解决方案


使用带有异步等待的简单 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;
  }
  


推荐阅读