得到了UnhandledPromiseRejectionWarning:错误:在调用同一个API 5000次时在nodejs上连接ETIMEDOUT错误

时间:2019-01-18 10:03:37

标签: javascript node.js api axios

我正面临UnhandledPromiseRejectionWarning:错误:连接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提取模块,但是得到了同样的错误。 真的很感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

这是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));