【问题标题】:got UnhandledPromiseRejectionWarning: Error: connect ETIMEDOUT error on nodejs while calling same api 5000 times得到 UnhandledPromiseRejectionWarning: E​​rror: connect ETIMEDOUT error on nodejs while call the same api 5000 次
【发布时间】:2019-06-12 13:53:03
【问题描述】:

我面临 UnhandledPromiseRejectionWarning: E​​rror: connect ETIMEDOUT 问题。

我会做的是这样的:

      const ops = [];
      const length = 5000;
      for (let x = 0; x < length; x++) {
        let op = axios.get("https://jsonplaceholder.typicode.com/todos/1");
        ops.push(op.data);
      }

      let res = await axios.all(ops);
      //console.log(res);

通过这几个响应返回然后得到错误,即

(node:7936) UnhandledPromiseRejectionWarning: Error: connect ETIMEDOUT 104.28.17.40:443
    at Object._errnoException (util.js:992:11)
    at _exceptionWithHostPort (util.js:1014:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
(node:7936) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 7856)

我不知道我从哪里得到这个问题以及为什么。 我也使用 NPM fetch 模块但得到了同样的错误。 任何帮助都非常感谢..

【问题讨论】:

  • 你正在调用 API 同时 5000 次。您正在发出 5000 个并发请求,因此您正在杀死服务器并且它正在拒绝您的请求。就这么简单。

标签: javascript node.js api axios


【解决方案1】:

您的请求正在超时,因为您向服务器发送了过多的请求。您应该将您的许多请求分成更小的批次,然后等待它们。

下面是它如何与fetch API 一起工作:

async function getall() {
    const ops = [];
    const length = 50; // reduced for snippet reasons ... :)
    const batchsize = 10;
    for (let x = 0; x < length; x+=batchsize) {
        const batch = [];
        for (let y = x; y < length && y < x + batchsize; y++) {
            const req = fetch("https://jsonplaceholder.typicode.com/todos/1")
                             .then((resp) => resp.json());
            batch.push(req);
        }
        // Wait for this batch to be completed before launching the next batch:
        ops.push(...await Promise.all(batch));
    }
    return ops;
}

getall().then((res) => console.log(res));

【讨论】:

  • 它在数据长度为 55 的情况下中断,在那里我们的循环运行 60 次而不是 55 次。
猜你喜欢
  • 2019-10-16
  • 2019-01-30
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 2020-12-16
  • 2021-11-14
  • 2020-02-14
  • 2021-11-19
相关资源
最近更新 更多