【问题标题】:How to perform HTTP requests in NodeJS with a Priority value?如何在 NodeJS 中使用 Priority 值执行 HTTP 请求?
【发布时间】:2021-11-19 09:03:54
【问题描述】:

我有一个对象数组,其中包含 url 和优先级编号(这是一个整数)。我需要按优先级值的升序执行http请求。例如,如果数组是这样的

const requestArray = [
  {
    url: "http://google.com",
    priority: 4
  },
  {
    url: "http://facebook.com",
    priority: 1
  },
  {
    url: "http://failed.example.gibberish.com",
    priority: 2
  }
];

首先,Facebook 应该被 ping 通,因为它的优先级为 1,并且记录了有效的响应(因为它是有效的),failed.example.gibberish.com 应该被 ping 通,因为它的优先级是 2,它应该被拒绝作为它的无效的 URL 和 google.com 应该被 ping,因为它具有最大的优先级数值,并且无论响应如何,它都应该被记录下来。我试图用 os.setPriority 来实现这一点(我是 Node.js 的新手。我不知道该怎么做)

演示:jdoodle.com/ia/jDx

如果没有优先级值,例如{ url: 'http://jsonplaceholder.typicode.com/posts' },我应该将 1 设置为该特定对象的优先级值,并且它应该位于任何其他优先级大于 1 的请求之前

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    映射缺失的优先级,然后在通过循环执行 HTTP 调用之前按优先级对数组进行排序。

    const requestArray = [
      {
        url: "http://google.com",
        priority: 4
      },
      {
        url: "http://facebook.com",
        priority: 1
      },
      {
        url: "http://failed.example.gibberish.com",
        priority: 2
      },
      {
        url: "http://nopriority.com"
      }
    ];
    
    const cleanRequests = requestArray
      .map((req) => req.hasOwnProperty('priority') ? req : { ...req, priority: 1 })
      .sort((a, b) => (a.priority > b.priority) ? 1 : -1);
    
    for (let request of cleanRequests) {
       const { priority, url } = request;
       console.log({ priority, url });
       // HTTP calls here...
    }
    

    【讨论】:

    • 我试过jdoodle.com/iembed/v0/jDQ,但仍然显示一些错误。不介意的话可以举个例子吗?
    • 您正在尝试调用未正确返回的内容的属性,console.log("Failed.", err.message, "Priority:", request.priority); 此处未定义请求。
    • 你能举个例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2016-04-08
    • 2012-07-16
    • 1970-01-01
    • 2018-06-02
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多