最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Understanding large parallel fetch requestresponse and timeout delays - Stack Overflow

programmeradmin4浏览0评论

Running this in terminal node test.js I was expecting console logs to print runtime close to 2000ms but instead it is well over 5000ms.

Why is that? Is the fetch queuing the requests? Could it be the OS limitation on parallel calls? I dont think the event loop is slowed that much with this simple loop though.

const run = async (i) => {
  const start = Date.now();
  const abortController = new AbortController();
  const timeout = setTimeout(() => {
    abortController.abort();
  }, 2000);
  try {
    const v = await (
      await fetch(";, {
        method: "POST",
        body: JSON.stringify([{}]),
        signal: abortController.signal,
      })
    ).text();
  } catch (e) {
    console.error(e);
  } finally {
    console.log(i, "runtime", Date.now() - start);
    clearTimeout(timeout);
  }
};
for (let i = 0; i < 10000; i++) {
  run(i);
}

Running this in terminal node test.js I was expecting console logs to print runtime close to 2000ms but instead it is well over 5000ms.

Why is that? Is the fetch queuing the requests? Could it be the OS limitation on parallel calls? I dont think the event loop is slowed that much with this simple loop though.

const run = async (i) => {
  const start = Date.now();
  const abortController = new AbortController();
  const timeout = setTimeout(() => {
    abortController.abort();
  }, 2000);
  try {
    const v = await (
      await fetch("https://slowendpoint", {
        method: "POST",
        body: JSON.stringify([{}]),
        signal: abortController.signal,
      })
    ).text();
  } catch (e) {
    console.error(e);
  } finally {
    console.log(i, "runtime", Date.now() - start);
    clearTimeout(timeout);
  }
};
for (let i = 0; i < 10000; i++) {
  run(i);
}
Share Improve this question edited yesterday VLAZ 29.1k9 gold badges62 silver badges84 bronze badges asked yesterday Nischit PradhanNischit Pradhan 4406 silver badges19 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

To set a timeout for the AbortController, you should create a signal object with a specific timeout. You can do that using: const signal = AbortSignal.timeout(2000); Then pass that signal object to the fetch call instead of abortController.signal.

发布评论

评论列表(0)

  1. 暂无评论