【问题标题】:how to use while loop with https node.js如何在 https node.js 中使用 while 循环
【发布时间】:2021-06-03 23:55:09
【问题描述】:

所以我想要做的是继续尝试获取数据检查我想要的值是否存在,如果它不存在,它将返回一个错误,然后重新执行操作,直到该值确实存在。 所以到目前为止我所拥有的是 https 调用

test = async() => {
  console.log("Hellow")
  now = new Date();
  const https = require("https");
  https.get("website",{ agent: proxyy },
    (res) => {
      var body = "";
      res.on("data", function (chunk) {
        body += chunk;
      });
      res.on("end", function () {
        var resp = JSON.parse(body);
        data_wanted = resp.data
        const desiredItem = data_wanted.find((item) =>
          item.name.includes("data")
        );
        console.log(desiredItem)
      });
    }
  );
};

我做了什么,但没有成功

while (flag = true ){
  let flag = false 
  try{
  await test()// test is the same function above
}catch(e){
  flag = true
}

}

因此 try catch 不会捕获任何错误,因此标志不会更改为 true ,并且由于某种原因,while 循环都不会单独工作

EDIT1 所以我认为由于 https 是异步的,try/catch 在 https 调用完成之前正在运行。

【问题讨论】:

  • 在完全工作之前我做过的有趣的事情,但我忘记了如何:p

标签: javascript node.js while-loop async-await try-catch


【解决方案1】:
async function test(){
   // log after 5 seconds
   setTimeout(()=>{console.log("ran after 5 sec")},5000)
   // and also return a string
   return "helloReturn";
}

async function infiniteLoop(){
// a while loop that never ends
   while(true){
      await test();
   }
}
infiniteLoop() // call the infinteLoop function

此代码永远不会记录任何内容,因为异步调用结果仅在主线程空闲时执行。 我会推荐你​​,查看这篇文章了解更多信息。 https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ 谈论解决方案您可以做的是在 setInterval 中传递您的函数,如果您找到该值而不是清除间隔,则检查该函数的结果。 让我知道您是否需要它的代码。 所以这里是代码,我认为它没有优化和正确的方法,但应该可以工作

interval = setInterval(test,1000) //  set interval for 1 sec function would be hoisted
async function test(){
 console.log("Hello")
  now = new Date();
  https.get("website",{ agent: proxyy },
    (res) => {
      var body = "";
      res.on("data", function (chunk) {
        body += chunk;
      });
      res.on("end", function () {
        var resp = JSON.parse(body);
        data_wanted = resp.data
        const desiredItem = data_wanted.find((item) =>
          item.name.includes("data")
        );
        console.log(desiredItem)
      });
    }
  );
    if(desiredItem)
        clearInterval(interval)
}

如果你在得到这个结果后需要做一些其他的事情,你可以在 if 语句中发出一个事件,并在你的代码中监听那个事件。 这个,你必须做的。检查 nodejs 中的事件发射器类。

【讨论】:

【解决方案2】:

我认为您在找到“数据”后忘记抛出错误。 也许你需要这样的东西

const desiredItem = data_wanted.find((item) =>
      item.name.includes("data")
 ); 
if (!desiredItem) throw Error('data not found');
return desiredItem

在执行功能上,你可以使用 try catch,也许是这样的

_execute = async () => {
  try {
   await test()
  } catch(e) {
    await _execute()
  }

}

并调用 _execute 函数

return _execute();

你也忘了在 https.get 上添加等待,你需要这样做。

await https.get()

【讨论】:

    【解决方案3】:

    接受的答案是一个聪明的答案,只是想给我的,因为它更容易理解

    test2 = async() => {
      console.log("Hellow")
      
      now = new Date();
     res =  await https.get("website",
      // { agent: proxyy },
        (res) => {
          // console.log(res)
          var body = "";
          res.on("data", function (chunk) {
            body += chunk;
          });
          res.on("end", function () {
            var resp = JSON.parse(body);
            data_wanted = resp
    
           
            const desiredItem2 = data_wanted.find((item) =>
              item.name.includes("data")
            );
          
           try{
            console.log(desiredItem2)
          }catch(e){
            console.log("couldnt find the id")
            test2()
          }
          });
        }
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2014-11-01
      • 1970-01-01
      • 2018-02-06
      • 2015-01-08
      相关资源
      最近更新 更多