1

我面临 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 模块但得到了同样的错误。任何帮助都非常感谢..

4

1 回答 1

1

您的请求超时,因为您正在用太多请求淹没服务器。您应该将您的许多请求分成更小的批次,然后等待这些请求。

以下是它与fetchAPI 的工作方式:

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

于 2019-01-18T10:22:45.833 回答